Yes, we must replace it++ with ++it--Andrey Karpov

I decided to find out if there is practical sense in writing ++iterator instead of iterator++ when handling iterators.

Is it reasonable to use the prefix increment operator ++it instead of postfix operator it++ for iterators?

by Andrey Karpov

From the article:

I will always write ++it. I did so before but I did it "just in case". Now I can see how useful it is because I regularly launch debug versions. In general, of course, ++it has a very slight influence on the running time. But if I don't make such small optimizations in different places of the code, it will be too late and the profiler won't help me. Bottlenecks will be spread throughout the code.

 

Add a Comment

Comments are closed.

Comments (2)

0 0

Mordachai said on Jan 30, 2015 08:01 AM:

I like a much simpler rationale: say what you mean.

I could write: return 0, 0, 0, 0, x;

And would the compiler optimize that to become return x? Yes, yes it would. But why the 7-hells would I write one thing when I meant another?

"Because I learned it that way" - that's a mindless, tiresome reason. If you learned to do something inefficiently, round-about, and pointlessly, then it is time to let that go, and join the conscientious people who write software with a eye towards professionalism, instead of "yeah, whatever."

0 0

Karl Hansson said on Feb 1, 2015 05:24 AM:

I agree with this article.

In feel that, out of the two types of functions, prefix or postfix (increment or decrement), the prefix increment version is almost always the more appropriate function since most of the time what people want is just to increment (or decrement) not to also save the previous state. Also when using the postfix versions in order to make the code look more compact it makes the code more difficult to read and reason about. In my opinion the postfix versions are often cases of premature cleverness MORE than using the prefix version would be premature optimization.

The only real good case to use postfix versions, that I can think of, is when using atomics, use prefix everywhere else and explicitly write a copy and a increment when needing to do so.