Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

In x = x + 1, is x evaluated twice? If so, does that mean in x += 1, x is only evaluated once? How are the two expressions evaluated in terms of compiler intermediate code?

For example, x++ could mean : take the location of x, load the contents of x into a register, and increment the value of x in memory.

Also I have read that x += 1 is useful when x is not a simple variable, but an expression involving an array. Any ideas why this is the case?

like image 596
user7 Avatar asked Sep 19 '11 13:09

user7


People also ask

Is X ++ faster than 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.

Which is better x ++ or x x 1?

Difference between x++ and x= x+1 in Java programmingx++ automatically handles the type casting where as x= x + 1 needs typecasting in case of x is not an int variable. See the example below.

What is the difference between x += 1 and x ++?

x + 1 returns the value of x + 1. x++ returns the value of x, and as a side effect the value of x is incremented at some point, not necessarily immediately.

Are x += 1 and x ++ the same?

You probably learned that x++ is the same as x = x+1 .


1 Answers

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
like image 193
sidyll Avatar answered Sep 18 '22 12:09

sidyll