Full disclosure - I was inspired. Is x + = faster than x = x + a?
Aside, I decided to test += vs -= . Simple tests show that they are 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 -= proportion to the given number:
long long sum = 0; for ( each number in the array ) if ( x[j] < k ) sum += x[j]; else sum -= x[j];
therefore, if k , say, small, -= will be called more often (duuuh). I tried with k = 2 , which would give a higher proportion of the called -= , and with k = 5 , which should give about the same amount -= and += .
Dotted line: a call -= about twice as fast as a call += . Why would it be more efficient in this case?
source share