aspose file tools*
The moose likes Performance and the fly likes For Loop Performance Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Performance
Bookmark "For Loop Performance" Watch "For Loop Performance" New topic
Author

For Loop Performance

Prathap
Greenhorn

Joined: Nov 23, 2006
Posts: 1
for (int i=0;i<arr.length;i++).

In fact, going through the loop counting downwards instead of upwards is faster:

for (int i=arr.length-1;i>=0;i--)

Whether performance is increased by traversing the loop downwards?
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

Hi,

Welcome to JavaRanch!

We have a strict policy on display names, which must be a real first and last name with a space between. No last initials, please.

Please go here and fix your display name up, pronto. Thanks, pardner!

Now, as to your question: micro-optimizations like this never make any sense in Java. What's faster on one JVM may be slower on another. More importantly, the HotSpot JVM looks for specific patterns in your bytecode and knows how to optimize them in a platform-specific way; if you use unusual coding idioms, like backwards loops, you may stop HotSpot (or another optimizing JVM or JIT) from doing its job.

So not only should you not do this, you should not even worry about little things like this -- in general, you'll only manage to slow things down by writing tricky code. Write clear, readable code, and trust the JVM to make it fast.


[Jess in Action][AskingGoodQuestions]
victor kamat
Ranch Hand

Joined: Jan 10, 2007
Posts: 247
Is the reason the for loop is faster is that one call is made to arr.length ?
victor kamat
Ranch Hand

Joined: Jan 10, 2007
Posts: 247
I have a another suggestion for the for loop:

What about:

for(int i=arr.length; --i>=0
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

Neither way is faster in general. Is my post above just too long, that you didn't bother to read it?
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: For Loop Performance