Is a += b more efficient than a = a + b in C?

前端 未结 7 1748
耶瑟儿~
耶瑟儿~ 2020-12-10 04:42

I know in some languages the following:

a += b

is more efficient than:

a = a + b

because it removes the n

7条回答
  •  感动是毒
    2020-12-10 05:07

    This is a compiler specific question really, but I expect all modern compilers would give the same result. Using Visual Studio 2008:

    int main() {  
        int a = 10;  
        int b = 30;  
        a = a + b;  
        int c = 10;  
        int d = 50;  
        c += d;  
    }  
    

    The line a = a + b has disassembly

    0014139C  mov         eax,dword ptr [a]   
    0014139F  add         eax,dword ptr [b]   
    001413A2  mov         dword ptr [a],eax   
    

    The line c += d has disassembly

    001413B3  mov         eax,dword ptr [c]   
    001413B6  add         eax,dword ptr [d]   
    001413B9  mov         dword ptr [c],eax   
    

    Which is the same. They are compiled into the same code.

提交回复
热议问题