Why is prefix incrementation (++x) faster than pos

2019-08-17 13:54发布

问题:

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++

回答1:

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.



回答2:

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.



标签: c gcc clang