Exact Duplicate:
Hopefully this is not too general or weird of a question. Also, couldn’t find it on Google, don’t whether this is just too dumb of a question or whether I fail at Google.
So, I forget where I read this from but, it said that using ‘++x’ (or whatever other variable) is somehow more optimized or whatever you might call this than, ‘x++’.
So, is this just a looks thing or is one truly faster? Like, they do the exact same thing so, that is why I am asking.
They’re doing different things. The first is pre-increment, and the second is post-increment. If you use either alone on a line, you won’t notice the difference. But if you do (for instance):
or
you will. With post-increment, you get the value, then increment. With pre-increment, you increment, then get the value. See http://en.wikipedia.org/wiki/++#Use_in_programming_languages for a brief explanation (they use JS as an example, but it applies equally to C#)
EDIT: By popular demand (and to refute a couple exaggerations), here’s a little about performance with primitives in C++. Take this example program:
It compiles (g++, just -S) to the below on x86. I have removed irrelevant lines. Let’s look at what’s happening and see if unnecessary duplicates are being made.:
We’re done.
As you can see, in this example, the exact same operations are required in each case. Exactly 2 movl, and 1 addl. The only difference is the order (surprised?). I think this is fairly typical of examples where the increment statement’s value is used at all.