Search code examples
c++performancestdstringcompound-assignment

Difference between string += s1 and string = string + s1


One of my programs is exceeding the time limit when I am using fans = fans + s[i], while when I am using fans += s[i] it is being accepted... Why does this happen? To Explain more , fans is a string and s is also a string so while iterating over string s i want only some characters of s so i am creating a new string fans.Now there are two ways in which i can add character to my new string fans. The Problem is mentioned below

fans = fans + s[i]; // gives Time limit exceeded 
fans += s[i];       // runs successfully

Solution

  • For built-in types a += b is exactly the same as a = a + b (except that a is evaluated only once), but for classes, those operators are overloaded and call different functions.
    In your example fans = fans + s[i] creates a temporary string, and assigns (moves) it to fans, but fans += s[i] does not create that temporary, hence it may be faster.