Yes, JVMs do this form of optimization. In your case, this will be the result of embedding and adaptive optimization in order to be value always, to be true. Consider the following code:
Foo foo = new Foo(true); foo.f();
Itβs trivial to prove to HotSpot that Foo always the actual instance of Foo on the call site f , which allows the virtual machine to simply copy-paste the method code, thereby eliminating virtual sending. After insertion, the example boils down to:
Foo foo = new Foo(true); if (foo.flag) { doSomething(); } else { doSomethingElse(); }
This again reduces the code to:
Foo foo = new Foo(true); foo.doSomething();
If optimization can be applied, therefore, it depends on the monomorphism of the call site foo and the stability of the flag on this call site. (The VM profiles your methods for such patterns.) The less VM can predict the outcome of your program, the less optimization there will be.
If the example was as trivial as the code above, the JIT will probably also remove the selection of the object and just call doSomething . In addition, for the trivial example case where the field value can be true trivial, the virtual machine does not need to optimize adaptively, but simply applies the above optimization. There is a great tool called JITWatch that allows you to learn how your code will be optimized.
Rafael winterhalter
source share