Possible Duplicate:
Is there a performance difference between i++ and ++i in C++?
Can anybody explain me why ++i is faster then i++ when we want to increment integer value I guess it might refer to any programming language.
Possible Duplicate:
Is there a performance difference between i++ and ++i in C++?
Can anybody explain me why ++i is faster then i++ when we want to increment integer value I guess it might refer to any programming language.
It absolutely is not. This is such a common fallacy which somehow keeps on perpetuating.
Note that, when "i" is an object, and an assignment is being made, "i++" will invoke a copy of that object (value before ++), whereas "++i" will not. Modern compilers will not perform a copy of the object if it is not needed.
Let's do some (pointless) benchmarking to show that it is irrelevant:
The Test Code: (Java)
public class TestIncrement
{
public static void main(String[] av)
{
int x = 0;
int y = 0;
long startTime;
// Postincrement
startTime = System.currentTimeMillis();
while ( startTime + 1000 > System.currentTimeMillis())
{
x++;
}
// Preincrement
startTime = System.currentTimeMillis();
while ( startTime + 1000 > System.currentTimeMillis())
{
++y;
}
// Output
System.out.println("Postincrement: " + x);
System.out.println("Preincrement: " + y);
}
}
And the Output:
Postincrement: 16039755
Preincrement: 16069900
When you have an expression like
k = i++;
k
gets the old value of i
before incrementation and i gets incremented. This copy creates the performance impact and is not needed with pre-incrementation. But sometimes both are not interchangeable. In this example with
k = ++i;
you will get another value for k.