Bookmark Topic Watch Topic
  • New Topic

for loop: Faster ( and more elegant ?)

 
victor kamat
Ranch Hand
Posts: 247
  • Mark post as helpful
  • send pies
  • Report post to moderator
This for loop is faster than the usual for loop ( and more elegant )

int sum = 0;
for (int i=arr.length; --i>=0; )
{
sum += arr[l];
}

I havent tested this for loop against the new Java 5 for loop.
 
Ajay Singh
Ranch Hand
Posts: 182
  • Mark post as helpful
  • send pies
  • Report post to moderator
whats the question here... failed to understand.
 
Cecil Phillip
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Report post to moderator
delete
 
Mark Newton
Ranch Hand
Posts: 129
  • Mark post as helpful
  • send pies
  • Report post to moderator
I might turn it into a question for him/her...

Is it quicker? Is it more elegant? Is it more maintainable!?! (Look at that 3 questions from one pointless statement! *is proud*)

Surely it's going to be compiled into pretty much the same thing, it's doing the same number of operations, after all, so surely it won't be any quicker? (I should mention that I have next-to-no understanding of the lower-level Java stuff, so I'm probably completely wrong here...)

More elegant? I guess if by 'elegant' you mean, 'harder to understand, easier to introduce bugs, but 1 character shorter', then yes, it's more elegant, but really?
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Report post to moderator
Oddly, we just had almost exactly the same conversation here in the (more appropriate) Performance forum. I'm going to close this; I refer you to my post in that other thread.

Note that as written, this loop isn't even correct; array.length isn't a valid array index.
[ January 15, 2007: Message edited by: Ernest Friedman-Hill ]
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Report post to moderator
Ummmm... yes it is correct. Or rather, it would be correct if we replace 'l' with 'i'. Note that --i >= 0 is evaluated at the beginning of the first iteration, so the first value that appears within the loop is arr.length - 1, which is fine. Apparently it's not considered very readable to most people.

[victor]: ( and more elegant )

You may have a hard time finding people who agree with you there.

[David]: so surely it won't be any quicker?

Don't be too sure. It may indeed be slightly quicker on some platforms. May also be slightly slower. Performance differences can be hard to predict, and can vary from platform to platform. What I will agree with is that performance differences in this code will usually be trivial compared to readability differences.

Anyway, as EFH said, more discussion is available here.
 
    Bookmark Topic Watch Topic
  • New Topic