by dmurray · 4y ago · 0 comments
Why would you still do be doing that work? If a value goes into a no-op, then the value isn't computed. (In theory - I'm sure it doesn't always work out 100% of the time in practice.)
The whole point of a JIT is that it can make assumptions. 'Assumption' is literally the term used in the JIT to track things like this.
If logging was part of the language, one could simply rule by fiat that arguments shall not be evaluated unless logging is enabled, but log4j is just another collection of user-defined classes, and gets no special treatment.
I'm not saying that when it comes to the JVM's optimization behaviors that I'd jump without checking that there's water on Chris's assurance, but I'm not saying I wouldn't either.
Assuming a global mutable variable will never change is generally not a safe assumption.
I suppose, at least in principle, that something like the GraalVM AOT compiler has the option to scan all of the code to verify that it never is mutated. But HotSpot cannot, because it only JITs code as it is loaded.
For example, an interface implemented by only 1 class might get the class inlined. If a second implementer pops up (which can happen at runtime for e.g. some dynamically generated class), all of this will get undone.
There was a series of small articles with all these things, but I can't seem to find them right now.
Put your logging level behind a switch point and C2 will treat it as a constant but still let it be changed - that works today.
Java HotSpot can make and verify that assumption. And switch code when the level changes.
If (a) DoExpensiveStuff());
Becomes
When modifyA() RecompileIfWithNewAValue();
As long as you call the initial if more often than you modify (a), you’re fine (and the JVM was able to see that you called your if 10k times without modifying the value of (a) even once)
Should the JIT call incrementAndReturnFooCount if debug logs are disabled? This is a long-recognized pitfall of C preprocessor macros that look like function calls but may simply be defined away, causing unexpected behavior.