I have decided to check the Java Compiler's perspicacity; thus, I have written a simple class.
public class Foo {
public Foo(boolean a, int b) {
if (a == true && a != false) {
b = 1;
}
}
}
I was wondering whether the compiler will optimize the condition to something simpler like:
if (a == true) {}
I compiled the class and then disassembled it with the javap
tool. When I took a look at the output, I was truly dumbfounded, because the compiler checks both of these conditions, what is clearly shown below.
Compiled from "Foo.java"
public class Foo {
public Foo(boolean, int);
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: iload_1
5: iconst_1
6: if_icmpne 15
9: iload_1
10: ifeq 15
13: iconst_1
14: istore_2
15: return
}
I am just curious, why is it executing redundant instructions, when it can be optimized to something simpler?
The javac
does no or only little optimization. The optimization occures during just-in-time (JIT) compilation of the bytecode.
This makes sense, because with this approach you can optimize differently for different target platforms and gain maximum optimization results.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With