aspose file tools*
The moose likes Performance and the fly likes for loop optimization Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of JavaScript Promises Essentials this week in the JavaScript forum!
JavaRanch » Java Forums » Java » Performance
Bookmark "for loop optimization" Watch "for loop optimization" New topic
Author

for loop optimization

mangpal singh
Greenhorn

Joined: Apr 25, 2006
Posts: 8
Case 1 :
for(int i=0;i<50000;i++){
System.out.print("l");
}

Case 2:
for(int i=50000;i>0;i--){
System.out.print("m");
}

Which of the two is faster ? If one of the two is faster, how much value does it add to have this optimization ?
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
You can measure elapsed time using the System.currentTimeMillis() method. Be sure to run the tests several times to see if the time varies substantially.


"I'm not back." - Bill Harding, Twister
Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14688
    
  16

From an assembler point of view, case 2 seems easier to track, by looking at the zero flag. Does it make it faster ? Don't know. Probably not. We're not in the 80's anymore anyway


[My Blog]
All roads lead to JavaRanch
Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14688
    
  16

That would be nice to send the results of Jim's suggestion
mangpal singh
Greenhorn

Joined: Apr 25, 2006
Posts: 8
As per Jim's suggestion, here is the time required for each case after running it 4 times consecutively. Surprisingly, case 2 takes more time except once.

Case 1 Case 2
844 1078
1469 1578
1438 1422
922 1141
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Well, it's not *that* surprising - it's typical code, so the JVM probably got optimized for it.

Moving to our Performance forum...


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

Note that the two loops use a different range of values for i: the first is 0...49999, while the second is 50000...1. In most cases, you'd have to change the test in the second one to be > -1 or >= 0, anyway -- so now you have to go off and time it again...


[Jess in Action][AskingGoodQuestions]
Bjorn Svensson
Greenhorn

Joined: Apr 26, 2006
Posts: 5
Originally posted by mangpal singh:
As per Jim's suggestion, here is the time required for each case after running it 4 times consecutively. Surprisingly, case 2 takes more time except once.

Case 1 Case 2
844 1078
1469 1578
1438 1422
922 1141


Also remember, the possibility that if you have non-fixed font you will
have a lot of extra lines in case 2 compared to case 1.
Avoid doing console I/O when doing low level performace tests
like this.
Shaan Shar
Ranch Hand

Joined: Dec 27, 2005
Posts: 1249

This is proved old mathametical algorithm that decreasing a number is faster then Increasing a number and the another fatcor is
about zero flag. which is easier then to compare every time you increase the number and then compare it to maximum value....



mangpal singh
Greenhorn

Joined: Apr 25, 2006
Posts: 8
Ernest,
The number of iterations performed by both the loops is same whether u go from 0 - 49999 or 50000 - 1.

Bjorn,
When we tried executing the loops without System.out.print() statements, the time taken is displayed as 0 in both cases.
William Brogden
Author and all-around good cowpoke
Rancher

Joined: Mar 22, 2000
Posts: 12821
    
    5
That myth about using the decrement instead of increment in a loop got started way back with Java 1.02 - I can't believe it is still circulating.

PLEASE! write your code for clarity and maintainability and ignore these bizarre "optimizations".

Bill (the old timer)
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

Originally posted by Bj�rn Julander:

Also remember, the possibility that if you have non-fixed font you will
have a lot of extra lines in case 2 compared to case 1.


Almost exactly the same lines are printed in both cases, but in a different order.
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

Originally posted by mangpal singh:

The number of iterations performed by both the loops is same whether u go from 0 - 49999 or 50000 - 1.


Indeed, I didn't imply otherwise. But the usefulness of the loop index differs: if you're going to use it as an array index, or an argument to List.get(), for example, then in the second case you'd need to either change the loop test or subtract 1 from the index before using it. What I'm saying is that in any real program, this may add additional overhead, and as long as you're microbenchmarking, you need to consider this.

Also, you need to read up on how HotSpot works before doing any kind of benchmark like this. If you put the loops in a separate method and invoke them multiple times, you'll see the performance improve. Just running something like this once in a test application gives an inaccurate impression of how it will act in a real program.
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by Ernest Friedman-Hill:


Almost exactly the same lines are printed in both cases, but in a different order.


Case 1 prints "l"s, case 2 "m"s. With a non-fixed font, the "m"s are likely to produce more line breaks...
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

Originally posted by Ilja Preuss:


Case 1 prints "l"s, case 2 "m"s. With a non-fixed font, the "m"s are likely to produce more line breaks...


My memory failed me during the discussion. I could've sworn the code was printing the loop index values themselves, one per line. Sorry, gang.
Peter Chase
Ranch Hand

Joined: Oct 30, 2001
Posts: 1970
Trying to measure performance of the loop itself, when the loop contains console output is totally doomed. The console output will take hugely longer than the loop itself.


Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.
Stefan Wagner
Ranch Hand

Joined: Jun 02, 2003
Posts: 1923

You can at least
to avoid the time for real output on the one hand, and prevent the super-optimization of removing the needles for-loop all together.

50.000 iterations are of course nothing.

And for microbenchmarks, you should reverse the code, and run both loops in reversed order too.
[ April 27, 2006: Message edited by: Stefan Wagner ]

http://home.arcor.de/hirnstrom/bewerbung
Isuru Sampath
Ranch Hand

Joined: Jun 26, 2003
Posts: 57
Originally posted by Ankur Sharma:
This is proved old mathametical algorithm that decreasing a number is faster then Increasing a number and the another fatcor is
about zero flag. which is easier then to compare every time you increase the number and then compare it to maximum value....


I don't think that there is any truth in it, at least for Java.

Test Code:




Results:

First Set:


If possible, please run the test yourself and see. Maybe you could post the results here...


No Winds No Waves
Mr. C Lamont Gilbert
Ranch Hand

Joined: Oct 05, 2001
Posts: 1170

Yes thank you Isuru. System.out is a blocking call or at least not thread friendly. Im not sure what was meant to be tested in the original post. The speed of the loop operation or the speed of repeated calls to System.out?

If one or the other were faster, it would be retarded by the call to System.out. Isuru's example removes this issue.
Stefan Wagner
Ranch Hand

Joined: Jun 02, 2003
Posts: 1923

Try Isurus code with java -server ForTest:
Isuru Sampath
Ranch Hand

Joined: Jun 26, 2003
Posts: 57
I think Stefan's results suggest that the operation results were cached.
Stefan Wagner
Ranch Hand

Joined: Jun 02, 2003
Posts: 1923

I guess the hotspot-compiler recognizes that the result of Math.sqrt (_dNum); is never used and the whole loop might be skipped.

I guess if you avoid this skipping by doing something more inside the loop, the difference between forward and backward iteration becomes negligible.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: for loop optimization