aspose file tools*
The moose likes Java in General and the fly likes for loop: Faster  ( and more elegant ?) Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Reply locked New topic
Author

for loop: Faster ( and more elegant ?)

victor kamat
Ranch Hand

Joined: Jan 10, 2007
Posts: 247
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

Joined: Dec 13, 2006
Posts: 182
whats the question here... failed to understand.
Cecil Phillip
Ranch Hand

Joined: Nov 05, 2001
Posts: 40
delete
Mark Newton
Ranch Hand

Joined: Jan 31, 2006
Posts: 129
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

Joined: Jul 08, 2003
Posts: 24187
    
  34

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 ]

[Jess in Action][AskingGoodQuestions]
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
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.


"I'm not back." - Bill Harding, Twister
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: for loop: Faster ( and more elegant ?)