javaloopsperformancepremature-optimization

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?


Solution

  • 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.