Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is ++i really faster than i++ in for-loops in java?

In java I usually make a for-loop like following:

for (int i = 0; i < max; i++) {    something } 

But recently a colleague typed it so:

for (int i = 0; i < max; ++i) {    something } 

He said the latter would be faster. Is that true?

like image 644
Binabik Avatar asked Jan 28 '11 18:01

Binabik


People also ask

What is faster than for loop in Java?

get(i); runs faster than this loop: for (Iterator i=list. iterator(); i.

Which loop is fastest in Java?

Iterator and for-each loop are faster than simple for loop for collections with no random access, while in collections which allows random access there is no performance change with for-each loop/for loop/iterator.

Which is more efficient i ++ or ++ i?

According to the Google C++ Style Guide, "when the return value is ignored, the 'pre' form ( ++i ) is never less efficient than the 'post' form ( i++ ), and is often more efficient."

Which for loop is faster?

The traditional for loop is the fastest, so you should always use that right? Not so fast — performance is not the only thing that matters. It is rare that you will ever need to loop over 1 million items in a frontend JS app.


1 Answers

No, it's not true. You could measure the performance by timing each loop for a large number of iterations, but I'm fairly certain they will be the same.

The myth came from C where ++i was regarded as faster than i++ because the former can be implemented by incremeting i then returning it. The latter might be implemented by copying the value of i to a temporary variable, incrementing i, then returning the temporary. The first version doesn't need to make the temporary copy and so many people assume that it is faster. However if the expression is used as a statement modern C compilers can optimize the temporary copy away so that there will be no difference in practice.

like image 180
Mark Byers Avatar answered Sep 21 '22 04:09

Mark Byers