+= or + is faster for primitive type?

Acoording to the rule of operator overloading
"+" is always more expensive than "+="
But what if those type like "int", "double" or "char"?
Are they also faster when I write the code like this?
1
2
3
4
5
6
7
8
9
10
int a, b, c;
...........
...........
a = b + c; //this way is faster?
...................
..................
//or this way is faster
a = 0;
a += b;
a += c;


thanks a lot
Last edited on
Think like a compiler.

a = b + c gets translated to something like:


   ld      $r1, [b]
   add   $r1, [c]
   st      [a], $r1


a = 0;
a += b;
a += c;


   st    [a], 0
   ld    $r1, [b]
   add [a], $r1
   ld    $r1, [c]
   add [a], $r1


3 memory accesses for the first one, 5 for the second. This is assuming no optimizations, which is a fair assumption
because you should never try to write code that depends on compiler optimizations. (It is very possible that a decent
optimizer would make the two very very similar so long as there are no lines in between the consecutive statements).
closed account (EzwRko23)

you should never try to write code that depends on compiler optimizations.


What a nice recipe to make any project a maintenance disaster.
Bad programmers don't trust compilers.
Good programmers know their tools and their limitations.
Optimizations mentioned in the upper post are so basic, you can safely assume they are done. If they are not, you are probably using your grandma's compiler.

I can agree with just a one thing: you should not write code whose asymptotic complexity depends on compiler optimizations you cannot enforce. Therefore you should not use tail-recursion in C++ (but you should in Haskell, LISP or Scala).

BTW:

Acoording to the rule of operator overloading
"+" is always more expensive than "+="


Not true. += actually can be very expensive, because of pipeline stall it can cause (write-after-read). The same applies to postincrementation and preincrementation - sometimes postincrementation is faster than preincrementation, especially for small objects.

Last edited on
Thanks to both of you, you guys really help me a lot
"think like a compiler" and
"Good programmers know their tools and their limitations. "

 
"+= actually can be very expensive, because of pipeline stall it can cause (write-after-read)"

so i should assume "+=" is cheaper than "+" when "+=" work with huge object
but not tiny object(without optimization)?


Topic archived. No new replies allowed.