Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 372
itachi Avatar asked May 22 '15 20:05

itachi


Video Answer


1 Answers

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.

like image 70
adjan Avatar answered Oct 01 '22 21:10

adjan