> Hmmm, is there any significant, practical difference?
> I think not. Remember, that was 40 billion iterations.
for standard types like int or double, it would not make any difference. the compiler knows everything about these types and can see that
a = a + b ; and a += b ; are equivalent and generate identical (optimized) code.
the case could be different for user defined types; for one the overloaded+ or += operators may not be inline and the compiler cannot make any assumptions about the equivalence between
a = a + b ; and a += b ; . if the operatos are inline, a good compiler can still optimize; even in this case, avoiding the creation of anonymous temporaries can improve performance.
int func_int_plus( int a, int b )
{
return a = a + b ;
}
int func_int_plus_assign( int a, int b )
{
return a += b ;
}
struct A
{
A( int xx, int yy ) : x(xx), y(yy) {}
A operator+ ( const A& that ) const
{ return A( x+that.x, y+that.y ) ; }
A& operator+= ( const A& that )
{ x += that.x ; y += that.y ; return *this ; }
int x ;
int y ;
};
A func_A_plus( A a, A b )
{
return a = a + b ;
}
A func_A_plus_assign( A a, A b )
{
return a += b ;
}
A& func_A_plus_assign_byref( A& a, const A& b )
{
return a += b ;
}
>c++ -O3 -S -fomit-frame-pointer operator.cc
an extract of the relevant parts of the assembly generated (gcc 4.2.3):
.file "operator.cc"
/////////////////////////////////
_Z13func_int_plusii:
.LFB2:
movl 8(%esp), %eax
addl 4(%esp), %eax
ret
.LFE2:
//////////////////////////////////
_Z20func_int_plus_assignii:
.LFB3:
movl 8(%esp), %eax
addl 4(%esp), %eax
ret
.LFE3:
//////////////////////////////////
_Z11func_A_plus1AS_:
.LFB9:
pushl %ebx
.LCFI0:
movl 8(%esp), %ebx
movl 12(%esp), %ecx
addl 16(%esp), %ebx
addl 20(%esp), %ecx
movl %ecx, %edx
movl %ebx, %eax
popl %ebx
output ret
//////////////////////////////////
_Z18func_A_plus_assign1AS_:
.LFB10:
pushl %ebx
.LCFI1:
movl 12(%esp), %ecx
movl 8(%esp), %ebx
addl 16(%esp), %ebx
addl 20(%esp), %ecx
movl %ecx, %edx
movl %ebx, %eax
popl %ebx
ret
.LFE10:
//////////////////////////////////
_Z24func_A_plus_assign_byrefR1ARKS_:
.LFB11:
movl 4(%esp), %eax
movl 8(%esp), %ecx
movl (%ecx), %edx
addl %edx, (%eax)
movl 4(%ecx), %edx
addl %edx, 4(%eax)
ret
.LFE11:
//////////////////////////////////