Possible Duplicate:
Is there a performance difference between i++ and ++i in C?
I heard it said that prefix incrementation is faster than postfix incrementation in C. Is this true and why?
++x vs x++
Possible Duplicate:
Is there a performance difference between i++ and ++i in C?
I heard it said that prefix incrementation is faster than postfix incrementation in C. Is this true and why?
++x vs x++
This is a ridiculous myth that gets repeated over and over. The two operators have semantic differences; one has as its result the old value and the other has as the result its new value. If you use this result, the code will have different behavior depending on which operator you used, and this may include performance differences if one behavior can be achieved more efficiently than the other. But if you don't use the result, x=x+1
, x+=1
, x++
, and ++x
are all identical.
Short answer no. Reason is that it's the same operation, just the order of evaluation of the statement is changed.
Example:
int a = x++;
int b = ++x;
Pseudo assembly:
mov a, x
inc x
inc x
mov b, x
This is a trivial example but even in larger examples the worst that can happen is a memory barrier enforced operation which doesn't allow the post increment value to be pushed or pulled past it which just adds an extra mov
operation due to a dependency or forced barrier. Most compilers optimize away this extra mov
in standard situations anyway using instruction reordering.