Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C#, which is more optimized, if that is the right word: ++x or x++? [duplicate]

Tags:

c#

Exact Duplicate:

In C# what is the difference between myint++ and ++myint?

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.

like image 742
Mashew Avatar asked May 14 '09 00:05

Mashew


2 Answers

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):

a = x++

or

a = ++x

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:

int main()
{
    int a;
    int x = 14, y = 19;
    a = x++;    
    a = ++y;    
}

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.:

        # Obvious initialization.
        movl    $14, -12(%ebp) 
        movl    $19, -16(%ebp)

        movl    -12(%ebp), %eax # This is moving "old x" to the accumulator.
        movl    %eax, -8(%ebp) # Moving accumulator to a.
        addl    $1, -12(%ebp) # Increment x (post-increment).

        addl    $1, -16(%ebp) # Increment y (pre-increment)
        movl    -16(%ebp), %eax # Move "new y" to accumulator.
        movl    %eax, -8(%ebp) # Move accumulator to a.

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.

like image 171
Matthew Flaschen Avatar answered Nov 15 '22 09:11

Matthew Flaschen


If you are optimizing at this level you are wasting time. There are surely some loops in your program that could get faster.

like image 45
jon skulski Avatar answered Nov 15 '22 07:11

jon skulski