This:
if (var) {
var = false;
}
Versus this:
var = false;
Is there a speed difference?
The first code contains a comparison, so your compiler maybe generate a java bytecode that looks like:
public static void main(java.lang.String[]);
Code:
0: iconst_1
1: istore_1
2: iload_1
3: ifeq 8
6: iconst_0
7: istore_1
8: return
For the second code the generated bytecode is shorter because the comparison is missing:
public static void main(java.lang.String[]);
Code:
0: iconst_1
1: istore_1
2: iconst_0
3: istore_1
4: return
The virtual machine needs more time for executing 8 commands in the first example than 4 commands in the second one. Although this difference should not be to high the second code is more clearly.
Put your code in a simple main method and compile the class. Then run a command prompt and change to java/bin
directory. To disassemble your class call javap -c path/to/YourClass.class >> path/to/bytecode.txt
. bytecode.txt will contain the java bytecode of your class.