Question:
C++ operator+=() vs operator+() x2?
Erick
2008-11-27 15:45:04 UTC
Which would be faster? Or are they near negligible? I am trying to get the fastest possible speed from this Windows utility. I checked the run time of each and even with a string of 10 commands or so, I get 0 ms. I don't know how they handle with higher quantities though.

for (int x(1); x    commands+=argv[x];
    commands+=" ";
}

or

for (int x(1); x    commands=commands+argv[x]+" ";
}
Four answers:
2008-11-27 16:36:03 UTC
In almost all cases, x += y is faster than or of equal speed to x = x + y. That is because x = x + y may create a temporary object (x + y) which will then need to be copied into x. With += on the other hand, the operation can be written so that no temporary object is created.



The compiler can sometimes optimize this away (such as when x and y are ints), however this is rarely true for user defined classes, as it is very difficult for the compiler to prove that x = x + y is exactly the same as x += y (they can be different if the class of x is poorly written).



So stick with +=, nothing to lose, but sometimes you may gain a small (or large) amount of performance.
Meg W
2008-11-27 15:50:55 UTC
First off, use a stringbuffer and convert it to a string after you're done. That WILL make a difference.



A good compiler will convert both to the same JVM code. A poor compiler will do better with option 2. More readable is

commands +=argv[x]+" ";
CinderBlock
2008-11-27 15:48:49 UTC
The compiler will likely optimize both to the same executable instructions.
Tizio 008
2008-11-27 15:51:23 UTC
what? does it compile? int x(1)?!

anyway it's basically the same, optimization make it hard to say and similar.



~~

it compiles?! hmmm


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...