Hi, i was wonder if the expression: ++j is faster than j++ Let's think to a for cycle: for(j=0; j<array.length; ++j) { foo.staff(); } at the last cycle, after the foo.staff() execution, what will happen will be that j will be incremented before to be considered for the condition. It should be different from the other expression, as in the case of j++, first j would be considered and then incremented. WFYI(Waiting for your impressions), Marco
Marco Tedone<br />SCJP1.4,SCJP5,SCBCD,SCWCD
Jim Yingst
Wanderer
Sheriff
Joined: Jan 30, 2000
Posts: 18652
posted
0
No, j++ and ++j are effectively equivalent in this case. Here's the sequence of events, for aray size 3: j = 0 is j < array.length? yes, 0 < 3, keep looping foo.staff(); ++j j is 1 is j < array.length? yes, 1 < 3, keep looping foo.staff(); ++j j is 2 is j < array.length? yes, 2 < 3, keep looping foo.staff(); ++j j is 3 is j < array.length? no, 3 !< 3, stop looping If you replace ++j with j++, it makes no difference here - the comparison with array.length is done separately. The only time ++j vs. j++ makes a difference is if you're doing something else with the expression as part of a larger expression, e.g. i = j++; is different from i = ++j; but j++; i = j; is not different from ++j; i = j; The three parts inside a for statement are separate expressions, and so it doesn't matter where the ++ in the third part is, it won't cross over into the second part.
"I'm not back." - Bill Harding, Twister
alzamabar
Ranch Hand
Joined: Jul 24, 2002
Posts: 379
posted
0
Jim, i understood that for the loop correctness nothing changes; i was just dealing with the 'internal JVM execution time' spent the ++j versus j++. In the latter to add 1 to j, the JVM takes evaluates j, while in the former it add simply 1. Is that correct? Marco
James Chegwidden
Author
Ranch Hand
Joined: Oct 06, 2002
Posts: 201
posted
0
There should be no differences between j++ and ++j in terms of speed.
Mr. C<br /> <br />Author and Instructor<br />My book:<br /><a href="http://www.aw-bc.com/catalog/academic/product/0,1144,1576761614,00.html" target="_blank" rel="nofollow">http://www.aw-bc.com/catalog/academic/product/0,1144,1576761614,00.html</a>
Dirk Schreckmann
Sheriff
Joined: Dec 10, 2001
Posts: 7023
posted
0
We could try to find out the easy way...I repeatedly get about 8800 milliseconds for the first loop and 5700 milliseconds for the second. This might trick one into thinking the second is performing better than the first. When I switch the ordering of the tests (so test i++ and then test ++i) the results of the first loop (which would then be the i++ test) are still about 8800 milliseconds and the results of the second test are still about 5700 milliseconds. So, the performance of these two operations appears to be equivalent.
I thought I remembered hearing that old C hackers used ++i instead of i++ because it avoided the creation of a temp variable or something like that. But isn't in nice that javac compiles out any difference...