Why is prefix incrementation (++x) faster than postfix incrementation (x++) in C? [duplicate]

吃可爱长大的小学妹 提交于 2020-01-06 06:55:12

问题


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.



来源:https://stackoverflow.com/questions/12190624/why-is-prefix-incrementation-x-faster-than-postfix-incrementation-x-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!