Skip to main content

loop unrolling,flattening howto and its performance

2 replies [Last post]
Joined: 2006-01-17
Points: 0

hello all,

what is the performance benefit of unrolling a loop.

for(int i=0;i

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
Joined: 2004-01-07
Points: 0

> for(int i=0;i > {
> int k = array[i];
> someMethod(k);
> k = array[i+1];
> someMethod(k);
> }

I did some self-made unrolling in encryption code I used, since I needed more speen on J2ME runtimes and it actually did work since those JVMs did not optimize anything.

However benchmarks showed me, that code generated by Hotspot was actually slower for the unrolled version, because HotSpot was not able to optimize the loop as perfect as before because of the more complex loop code.
Hotspot is the name of the compiler working inside of Sun's default java runtime.

I would in general stay away from such optimizations and use the server jvm. Such stuff is really a waste of resources, except you work for special jvms like j2me/javacard.

lg Clemens

Joined: 2005-07-11
Points: 0

In your case, you cut the number of compares in half
and eliminate half of the back branches.

Most modern Java JITs will perform this operation for you. IMHO, you should never do unnatural things to your code just for performance, as it makes your code more difficult to understand and maintain and it may even make it more difficult for the JIT to do a good job optimizing the code. Of course, there are always exceptions.

If you find that hand unrolling is performing better than the unrolling that the JIT performs, then post a follow-up message. It may be due to the complexity of the body of the loop. Note, make sure that you've provided enough time for the JIT to perform the compilation (use -XX:+PrintCompilation and watch for your method getting compiled) and make sure you try -server.