Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java compiler doesn't optimize out static final string. Why?

I have the following code in my app:

  public static final boolean DEBUG = true;
  public static final boolean REL = !DEBUG;

  private static final String DEBUG_OR_RELEASE = (REL) ? "RELEASE_VER" : "DEBUG_VER";

I thought that the Java compiler will eliminate the "DEBUG_VER" string completely from the resulting .apk file (when exported via Proguard) but when I examine the .apk file, I see the "DEBUG_VER" string in there.

Why? What am I missing? What did I do wrong?

like image 537
ateiob Avatar asked Mar 22 '26 10:03

ateiob


1 Answers

Compilation to java bytecode is not making optimization (except a very few exceptions).

Many books state for simplification that the 'compilation' phase is when optimization occurs, but it is wrong. When the optimization really takes place, is while bytecode files are processed by JVM. So for the clearance: optimization may occur at the time of compilation bytecode to machine native code, which is done by JVM tools.

Sometimes there is no optimization at all (JVM works in interpreting mode). Sometimes there is some optimization made by JIT (Just In Time complier). And sometimes adaptative optimizer takes care of the optimization (not only optimizing but also profiling code execution in case of additional operations to be performed).

So finally, there is nothing wrong with your file. It's just how java world works.

"But why?" -- you may ask. The reason to keep this 'useless' information in bytecode is because you would never be sure how many code can you eliminate so the optimization provided by different JVM could still work efficient. The best way is just to not erase any information and let the optimizers to do their job.

like image 60
msi Avatar answered Mar 25 '26 00:03

msi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!