Is x += 1 more efficient than x = x + 1?

时光怂恿深爱的人放手 提交于 2019-11-27 15:33:01

In most compilers these would be identical

Just to give you a "real-world" example, consider this program:

int main()
{
    int i = 0;
    i += 1;
    i++;
    i = i + 1;
    return 0;
}

Compiling it with GCC, in Darwin 11 with the following flags:

  • -S stop in assembler
  • -m32 to 32-bit platform, just to simplify things a bit

Will generate the following program, except for the comments and blank lines which I added. Take a look specially in the comments.

        .section        __TEXT,__text,regular,pure_instructions
        .globl  _main
        .align  4, 0x90
_main:
        pushl   %ebp              # cdecl function stuff
        movl    %esp, %ebp        #
        subl    $12, %esp         # get room for variables    
        movl    $0, -12(%ebp)     # i = 0;

        ; i += 1
        movl    -12(%ebp), %eax   # load i in register a
        addl    $1, %eax          # add 1 to register a
        movl    %eax, -12(%ebp)   # store it back in memory

        ; i++
        movl    -12(%ebp), %eax   #
        addl    $1, %eax          # just the same
        movl    %eax, -12(%ebp)   #

        ; i = i + 1
        movl    -12(%ebp), %eax   #
        addl    $1, %eax          # just the same
        movl    %eax, -12(%ebp)   #

        movl    $0, -8(%ebp)
        movl    -8(%ebp), %eax
        movl    %eax, -4(%ebp)
        movl    -4(%ebp), %eax
        addl    $12, %esp
        popl    %ebp
        ret

.subsections_via_symbols

Why is x += 1 more efficient than x = x+1?

It isn't.

Why is x++ more efficient than x += 1?

It isn't.


The reason for preferring x += 1 to x = x+1 comes about when x is replaced with a much longer identifier, or perhaps a field in a class or struct. In that situation, the x += 1 version is more readable and even more importantly avoids the pitfalls of repeating yourself.

lxt

So there are already some questions that cover what you're asking here:

x=x+1 vs. x +=1

Incrementing: x++ vs x += 1

Which is faster? ++, += or x + 1?

The bottom line is that in most but not all languages the compiler is going to make them identical anyway, so there's no difference in efficiency. The questions above go into a fair bit of detail on the subject.

With gcc, you can get the assembler code with gcc -S foo.c. I tried it with x += 1 and x = x + 1 and it was the same.

Because it takes 4 characters to write rather than 5.

This is the only way in which x+=1 is "more efficient" than x=x+1. However the += operator does have a few other advantages, like the fact that (x)+=1 works in macros where x is an expression that may have side effects which you want to avoid evaluating more than once...

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