1

I was working on a change in some old system. To guarantee I was building on the correct source I ran a comparison between class files in an existing jar and those in the new jar. I decompiled some class which has differences in binary form, and below was found.

Java source decompiled from old class and the source code of the new class file that I built on are the same as below:

 if(user != null){
     ...
     if(user !=null){
     ...
     }
 }

Java source decompiled from the new class file: the inner null checking does not exist. Note that there is no change to 'user' between the two ifs:

 if(user != null){
     ...
     ...
     ...
     ...
 }

So, I want to know if the null checking was removed by the Java compiler as an optimization? If yes, in what cases (i.e., javac version, compile options) will it happen?

TT.
  • 15,774
  • 6
  • 47
  • 88
Jammy Lee
  • 1,496
  • 1
  • 14
  • 32
  • 2
    Keep in mind that between your two ifs the user could have been changed AND the 2nd if still is vital to your code. So this would only be an optimization if between those two ifs the user isn't changed in some way. – Aron_dc Jan 19 '16 at 10:21
  • @Aron_dc It is an optimization that was done by the compiler as OP writes. Personally I guess that there is no change of that reference in between. Otherwise many many projects would fail when compiled with the newer version. – Fildor Jan 19 '16 at 10:26
  • 1
    Take a look here : http://stackoverflow.com/questions/5981460/optimization-by-java-compiler – hasnae Jan 19 '16 at 10:35
  • @Aron_dc , yes , it true, there is no change of 'user' between the two ifs, questions updated – Jammy Lee Jan 21 '16 at 03:22
  • here is an interesting article: https://briangordon.github.io/2014/01/javac-optimizations.html you may find part of your answer there – Pooya Jan 21 '16 at 03:44
  • Rather than "an optimization" better said "a translation". javac never would create or add anything that you code didn't contain but translates its to a version that jvm could understand and usually this "translation" means an optimization. In example, if you create code with JDK 1.6 using StringBuilder and you generate classes with JDK 1.4 compatibility it will translate this to version that doesn't use StringBuilder (that didn't exist at JDK 1.4) but would keep the same functionality. – Facepalmed Jan 21 '16 at 11:28
  • In the other hand, if you have a pack of nested loops doing unnecessary iterations and checkings like "if(a == a)" or so on, it will be kept and this unefficient code will remain to shame you for the eternity :) – Facepalmed Jan 21 '16 at 11:29

0 Answers0