x=x+1 vs. x +=1

后端 未结 17 1103
独厮守ぢ
独厮守ぢ 2020-12-29 02:57

I\'m under the impression that these two commands result in the same end, namely incrementing X by 1 but that the latter is probably more efficient.

If this is not c

相关标签:
17条回答
  • 2020-12-29 03:21

    I wrote a simple console app:

    static void Main(string[] args)
    {
        int i = 0;
        i += 1;
        i = i + 1;
        Console.WriteLine(i);
    }
    

    I disassembled it using Reflector and here's what i got:

    private static void Main(string[] args)
    {
        int i = 0;
        i++;
        i++;
        Console.WriteLine(i);
    }
    

    They are the same.

    0 讨论(0)
  • 2020-12-29 03:21

    Back in the early 1980s, one of the really cool optimizations of the Lattice C Compiler was that "x = x + 1;", "x += 1;" and "x++;" all produced exactly the same machine code. If they could do it, a compiler written in this millenium should definitely be able to do it.

    0 讨论(0)
  • 2020-12-29 03:24

    If x is a simple integer scalar variable, they should be the same.

    If x is a large expression, possibly with side effects, +=1 and ++ should be twice as fast.

    Many people concentrate on this kind of low-level optimization as if that's what optimization is all about. I assume you know it's a much bigger subject.

    0 讨论(0)
  • 2020-12-29 03:25

    Something worth noting is that +=, -=, *= etc. do an implicit cast.

    int i = 0;
    i = i + 5.5; // doesn't compile.
    i += 5.5; // compiles.
    
    0 讨论(0)
  • 2020-12-29 03:26

    are the same.

    x=x+1 
    

    is mathematical seen a contradiction whereas

    x+=1
    

    isn't and is light to be typed.

    0 讨论(0)
  • 2020-12-29 03:27

    On x86, if x is in register eax, they will both result in something like

    inc eax;

    So you're right, after some compilation stage, the IL will be the same.

    There's a whole class of questions like this that can be answered with "trust your optimizer."

    The famous myth is that
    x++;
    is less efficient than
    ++x;
    because it has to store a temporary value. If you never use the temporary value, the optimizer will remove that store.

    0 讨论(0)
提交回复
热议问题