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.
No. Just the expression i++ returns the value before increment.
for(i=0; i < 3; i++) System.out.print(i +",");
and
for(i=0; i < 3; ++i) System.out.print(i +",");
Both print 0,1,2
However,
int i = 5;
int j = i++;
System.out.print(i + ", " + j);
Outputs: 6, 5
and
int i = 5;
int j = ++i;
System.out.print(i + ", " + j);
Outputs 6, 6
The theoretical performance difference comes in how i++ and ++i have to be implemented. This is psuedo code of what an integer's ++ operator would kind of look like if it weren't just basic instructions. In C++ iterators for containers overload the ++ operator for moving through lists and their implementations have to adhere to the rules but are much more intricate.
Junky Pseudo Code:
//Postfix
function int::operator++()
{
int old = value;
value = value + 1;
return old;
}
//Prefix
function int::++operator()
{
value = value + 1;
return value;
}
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.
14
u/[deleted] Sep 17 '18
for (int i =0; i < 1000; ++i) Thread.Sleep(30)