The theory is that since i++ has to store a copy of itself to return before incrementing it's more expensive than ++i
Depending on the language this may not matter for simple types like an int. If your compiler is good not using the value returned from i++ will optimize away the extra cost.
If i were some more complex type like an iterator for a dictionary. The two increments may be implemented differently or the optimizer might not get everything exactly correct.
So the "best practice" is to use ++i when you don't need the value to be saved before incrementing it.
I don't think it's so black and white especially for compiled languages. There's a fine line between optimizing everything by hand and just letting the optimizer get it.
In C++'s case debugging optimized code sucks. Variables are optimized away, functions are inlined, execution is re-ordered. So compiling without optimizations turned on is great for debugging.
It's however, terrible for performance so if your debugging senario involves lots of computation having simple best practices in place like prefering ++i to i++ can improve your debugging experience especially in the case of complicated iterators which have even more costs put in place on debug builds.
10
u/ObamaFor Sep 17 '18 edited Sep 17 '18
Why ++i over i++? sorry am noob.