This:
if (var) {
var = false;
}
Versus this:
var = false;
Is there a speed difference?
I am late to the game on this one but I wrote this test class to answer a similar question.
package SpeedTests;
import java.text.NumberFormat;
import java.util.Locale;
public class BooleanSpeedTest {
public static void main(String[] args) {
boolean BoolTest = true;
long LongLoop = 100000;
long TrueLoopCount = 0;
long FalseLoopCount = 0;
long TimeTotal = 0;
long startTime;
long endTime;
for(int intLoopA = 1; intLoopA < 6; intLoopA++) {
LongLoop = LongLoop * 10;
TimeTotal = 0;
System.out.println("");
System.out.print(
NumberFormat.getNumberInstance(Locale.US).format(LongLoop) + " - ");
for(int intLoopM = 0; intLoopM < 20; intLoopM++) {
TrueLoopCount = 0;
FalseLoopCount = 0;
startTime = System.currentTimeMillis();
for(long LoopCount = 0; LoopCount < LongLoop; LoopCount++) {
if(!BoolTest) {
TrueLoopCount++;
}
else
FalseLoopCount++;
}
endTime = System.currentTimeMillis();
System.out.print( (endTime - startTime) + "ms ");
TimeTotal += ((endTime - startTime) );
}
System.out.print(" AVG: " + (TimeTotal/20));
}
}
}
My results: Avg time/billion (ms) Notes Time Per Loop
if(BoolTest) 443 When False 0.00000443
if(BoolTest) 443 When True
if(BoolTest == false) 443 When False
if(BoolTest == false) 442 When True
if(!BoolTest) 438 When False
if(!BoolTest) 441 When True
(BoolTest ? Var++ : Var--) 435 When True
(BoolTest ? Var++ : Var--) 435 When False