itachi
itachi

Reputation: 3597

Strange optimization of "if" conditions in Java

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?

Upvotes: 9

Views: 187

Answers (1)

adjan
adjan

Reputation: 13652

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.

Upvotes: 14

Related Questions