While I canβt say for sure what the jit compiler does, the optimization you ask (to determine that it is safe to skip the body of the loop completely) is actually very difficult to do, and therefore I doubt very much that it is done. This is true, regardless of the fact that String is a "rudimentary Java class."
To better understand, first suppose that instead of String we instantiate an arbitrary class Foo. It would be safe to skip the creation of all these Foo objects if we knew two things: calling new Foo() had no observable side effects; and that no references to Foo βescapedβ the body of the loop.
The observed side effect would be something like setting the value of a static member (for example, if the class Foo contained a static number of all times Foo() ). An example of reference escaping would be if the this variable inside Foo() were passed somewhere else.
Note that just looking at Foo() not enough, you need to look at the Foo supererclass constructor (and the whole path to the chain on Object). And then you need to look at all the code that runs when each of these objects is initialized. And then look at all the code called by this code. This would be a huge analysis to do just-in-time.
public class Foo extends Bazz{ static int count = 0; public Foo(){
You might think that we should just let javac do this analysis and optimization for us. The problem is that there is no way to guarantee that the version of Foo() that was in the classpath at compile time is the same as the version of the tpath class at runtime. (This is a very valuable Java feature - it allows me to move my application from Glassfish to Tomcat without recompiling). Therefore, we cannot trust the analysis performed at compile time.
Finally, understand that String is no different from Foo. We still needed to perform this analysis, and we cannot do this analysis in advance (that I can update the JRE without recompiling my applications)
source share