Full disclosure - I was inspired by Is x += a quicker than x = x + a?
That aside, I decided to test +=
vs -=
. Simple tests reveal they're about the same. Then I tried something similar to:
std::vector<int> x;
for (int i = 0 ; i < 10000 ; i++)
x.push_back(rand()%10);
and call +=
and -=
proportionally to a given number:
long long sum = 0;
for ( each number in the array )
if ( x[j] < k )
sum += x[j];
else
sum -= x[j];
so, if k
is, say, small, -=
would get called more often (duuuh). I tried with k = 2
which would give a higher proportion of -=
called, and with k = 5
, which should yield about the same number of -=
and +=
.
The punchline: calling -=
is about twice as faster than calling +=
. Why would it be more efficient in this case?