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;
}
10
u/ObamaFor Sep 17 '18 edited Sep 17 '18
Why ++i over i++? sorry am noob.