If you're interested in the amount of time saved by adding the conditional, have a look at this:
Below I have written out both versions of your code, and the corresponding generated java bytecode.
boolean b = true;
if(!b)
b=true;
0: iconst_1
1: istore_1
2: iload_1
3: ifne
6: iconst_1
7: istore_1
8: return
boolean b = true;
b=true;
0: iconst_1
1: istore_1
2: iconst_1
3: istore_1
4: return
As you can see, the direct reassignment of the boolean
generates less bytecode.
At first, this may seem like the answer. Unfortunately, it isn't that simple. See runtime environments do this fancy thing called branch prediction. If a line of code is being run continuously, the JVM will attempt to "predict" the outcome of the conditional.
This can be a really good thing, or a really bad thing. Your expected values of the boolean
, the number of times it is to be checked in rapid succession and whether it is likely to remain a certain value through many calls will determine whether you should add the conditional statement or not.