Code:

int x = 1; if (x != 2) { int y = 2;} int z = x + y; System.out.print(z); 

As a matter of fact, this code, in spite of if, is equivalent to this in any case:

 System.out.print(3); 

And now the question itself What will write in the compiled java file? Short or long version of the code?

  • one
    And you compile and look. - a_gura
  • I think will miss - Gorets
  • ten
    This will not compile, the variable y not visible outside the block, is it not? - VladD
  • In general, it depends on the optimizer, of course. And so it is right. Is the result the same? - VladD pm
  • I do not think that something will be fundamentally changed. Expressions of the type a = 2 + 3 are well optimized; Well ... maybe even in a row when determining. Throw out operators - I do not think. - SilverIce

1 answer 1

Little experiment.

Option 1

 public static void main(String[] args) { int x = 1; int y = 0; if (x != 2) { y = 2;} int z = x + y; System.out.print(z); } 

No changes. 1 in 1.

Option 2

Source:

 public static void main(String[] args) { int x = 1 + 4; int y = 0 + x; if (x != 2) y = 2; int z = x + y - y + y - x + x; System.out.print(z); } 

decompiling:

 public static void main(String[] args) { int x = 5; int y = 0 + x; if (x != 2) y = 2; int z = x + y - y + y - x + x; System.out.print(z); } 

As expected, it took only an obvious addition.

Option 3

But with constants all the more interesting:

Source:

 public static void main(String[] args) { final int x = 1 + 4; final int y = 1 + x; final int z = x + y - y + y - x + x; System.out.print(z); } 

Decompile:

 public static void main(String[] args) { int x = 5; int y = 6; int z = 11; System.out.print(11); } 

Here the optimizer has already pulled as he wanted)

JDK Tools 1.7.0.9 + JD 0.6.2

  • 3
    not lazy =) well done - Gorets
  • It is strange that the optimizer generally left x, y and z. - VladD
  • In this case, it is better to look at bytecode rather than compiler + decompiler rather than the result of the link. - Costantino Rupert
  • @ Kitty: in .NET, EMNIMS, most of the optimization is done by jitter. Maybe in Java as well? - VladD
  • one
    @ Kitty: yep. Especially if you consider that the jit-optimizer for choosing its parameters is guided by certain statistics about which code branches are more important, processor speed, wind direction and moon phase. - VladD