Why the former is more optimal than the latter (answer preferable in plain English)?
Why this method is better
str = "hello ";
str2 = "world";
str += str2;
than
str = "hello ";
str2 = "world";
str = str + str2;
Why the former is more optimal than the latter (answer preferable in plain English)?
Why this method is better
str = "hello ";
str2 = "world";
str += str2;
than
str = "hello ";
str2 = "world";
str = str + str2;
The question here is, what better means. Let us assume, less complex assembler code and maybe an advantage in speed and a little bit in size.
It also depends a little bit on the qualifiers of the variable and very much on the compiler and the compiler options.
The naive approach and understanding is always: For x = x + y;
, at first the result of the addition will be calculated and then this result (a temporary) will be assigned to the original variable. For x += y
the string y will directly be appended to x.
In case of strings, the addition is implemented by calling the strings append function.
And, as said, if you do not switch on compiler optimization, there will first be an append operation and then an assignment. You may check the generated assembler code. So the x = x + y
is indeed more complex than the x += y
. However, if you switch on compiler optimizations (e.g. -O3 for gcc), there will be no difference.
There maybe other interpretations for "better". More readable, or better maintainable, or fitting to some coding guidelines or some operator overload constraints. So somehow hard to give a convrete answer and the result would maybe be opinion based.