Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

For Loop Performance

 
Prathap
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
victor kamat
Ranch Hand
Posts: 247
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is the reason the for loop is faster is that one call is made to arr.length ?
 
victor kamat
Ranch Hand
Posts: 247
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Neither way is faster in general. Is my post above just too long, that you didn't bother to read it?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic