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?
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?
In Java there should be no difference - any modern compiler* should generate the same byte code (just an
iinc
) in both cases since the result of the increment expression is not being used directly.There is a third option, still the same byte code*:
* tested with Eclipse's compiler
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 thani++
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.Even if it is, which I very much doubt, your colleague should really have better things to spend his time learning than how to optimise a loop expression.
This question needed some Java byte code. Consider the following code:
Now compile it and disassemble it:
loop1()
andloop2()
have the same byte code.Try this in your environment
Mine gives me
So even if it is not that much, I asume there is a difference
For any reasonably capable optimizer, they will be exactly the same. If you aren't sure, look at the output bytecode or profile it.