Main Content

Expensive use of non-member std::string operator+() instead of a simple append

The non-member std::string operator+() function is called when the append (or +=) method would have been more efficient

Since R2020b

Description

This defect occurs when you append to a string using the non-member function std::string operator+(), for instance:

std::string s1;
s1 = s1 + "Other";

Risk

The operation:

s1 = s1 + "Other";
invokes the non-member function std::string operator+() for the string concatenation on the right-hand side of the assignment. The function returns a temporary string, which is then assigned to s1.

Directly calling the member function operator+=() avoids the creation of this temporary string and is more efficient.

Fix

To append to a string, use the member function operator+=(), for instance:

std::string s1;
s1 += "Other";
or the member function append, for instance:
std::string s1;
s1.append("Other");

Performance improvements might vary based on the compiler, library implementation, and environment that you are using.

Examples

expand all

#include <string>

void addJunior(std::string &name) {
    name = name + ", Jr.";
}

void addSenior(std::string &name) {
    name += ", Sr.";
}

void addDoctor(std::string &name) { 
    name.append(", MD");
}

In this example, the checker flags the string append in the addJunior function, but not the ones in the other two functions. If the function addJunior is called several times in a loop, creation of a temporary string each time can be a significant performance issue.

Result Information

Group: Performance
Language: C++
Default: Off
Command-Line Syntax: EXPENSIVE_STD_STRING_APPEND
Impact: Low

Version History

Introduced in R2020b