Loop compilation weirdness
John Rose
John.Rose at Sun.COM
Wed Dec 3 14:22:22 PST 2008
On Dec 3, 2008, at 11:53 AM, Scott Oaks wrote:
> So my long-winded question is why the loop is compiled differently
> when
> we return out of the if statement rather than if we process a simple
> statement in the if statement.
Here's a short answer: Simpler loops are optimized better.
What's a simple loop (besides fewer statements)?
Loops with more loop invariant and loop index values are generally
simpler.
Loops with fewer internal control merges are generally simpler.
In the case of your code, the slower loop has a conditional path that
merges back into the loop body.
At that merge point, the 'boff' value becomes something much more
complicated than a simple index variable.
(Even though it is a variable in the heap, the optimized loop
probably keeps it in a register most of the time. The Java memory
model is designed to allow this.)
Note that I said "internal control merges" not the more obvious
"internal branches of control". If a loop has a branch that exits
the loop, it does not greatly complicate the optimization of the
loop. For example, a conditional branch that changes the value of a
loop invariant or index variable and then exits the loop does not
destroy the quality of the variable for the loop body. Only a
subsequent merge back into the loop body will do this. (This is a
consequence of SSA-based optimization.) It is common for even simple
Java loops to have tens of exit points, most of them for never-taken
potential exceptions (null check, cast, range check, etc.).
But this is all off-the-cuff. I haven't compiled your code. For
better information in your particular case, use the disassembler:
http://wikis.sun.com/display/HotSpotInternals/PrintAssembly
Good luck,
-- John
P.S. The System.arraycopy intrinsic is heavily optimized, and in
some cases is faster than a hand-written loop.
For NIO, there is also sun.misc.Unsafe.copyMemory, which can copy any
combination of {C heap, Java heap} to {C heap, Java heap} arrays.
This uses the same intrinsic optimizations as System.arraycopy.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.openjdk.java.net/pipermail/hotspot-dev/attachments/20081203/0f15f596/attachment.html
More information about the hotspot-dev
mailing list