Efficiency versus intent
Every once in a while I see a Usenet discussion about whether it is better to write i++ or ++i in contexts such as</p>
Every once in a while I see a Usenet discussion about whether it is better to write i++ or ++i in contexts such as
for (int i = 0; i < n; ++i) { /* ... */ }
Invariably, there will be at least one remark to the effect that of course ++i is better because it is more efficient.
Such remarks miss what I think are three important points.
First, it is far from obvious that ++i is more efficient than i++, at least where integer variables are concerned. I think that the last time I encountered a compiler that generated slower code for i++ than for ++i, assuming of course that the result is discarded, was before 1980.
Second, even if there were a significant difference in speed between ++i and i++ in isolation, it is far from obvious that the difference would be worth worrying about in context. If this loop does any significant work, almost none of its time will go into incrementing the control variable. Moreover, on many processors, the variable will be incremented in parallel with other operations, so there will be no difference at all. Unless you're willing to measure the loop in context, I don't think it's reasonable to expect a significant difference between the two usages.
Third, and most important, I think the speed difference is much less important than the design difference. ++i asks the computer to increase the value of i by 1, and then yield the variable i. In contrast, i++ asks the computer to copy the value of i, increase the value if i by 1, and then yield the copy of the original value.
So the question one should be asking is not which of these two operations is faster, it is which of these two operations expresses more accurately what you are trying to accomplish. I submit that if you are not using the value of the expression, there is never a reason to use i++ instead of ++i, because there is never a reason to copy the value of a variable, increment the variable, and then throw the copy away.
In other words, there is nothing at all wrong with using i++ in, for example, array indices such as a[i++]. In this context, we really do intend to use the original value of i as the index, and increment the variable after we're done with it. In a context such as the original for statement, however, we are specifying work to be done that we know we will not need.
It is that design inefficiency that I consider important, not the nebulous execution inefficiency that most people seem to want to discuss.
About the Author
You May Also Like
2024 InformationWeek US IT Salary Report
May 29, 20242022 State of ITOps and SecOps
Jun 21, 2022