Expensive use of
std::string method instead of more efficient
overload
An std::string method is called with a string literal of known
length, instead of a single quoted character
Since R2021a
Description
This defect occurs when you invoke certain std::string methods with a
string literal of known length instead of a single quoted character. When certain
std::string methods are called with a string literal, the method must
compute the length of the literal even though the information is known at compile time.
Polyspace flags such calls as inefficient. For instance, Polyspace® flags the first two calls to
std::string::find:
std::string str;
//...
str.find("A");//Inefficient
//...
str.find("ABC",offset,1);//Inefficient
str.find('A');//Efficient
std::string methods are invoked
by using a string literal of known length instead of a single quoted character:
findrfindfind_first_offind_last_offind_first_not_offind_last_not_ofreplaceoperator=operator+=starts_with(C++20)ends_with(C++20)
Risk
In some cases, you can call std::string methods with either a string
literal or a single quoted character. In these cases, it is inefficient to call the
std::string methods with string literal because such calls force the
compiler to compute the lengths of the string literals, which is already known before
runtime. Because std::string methods are frequently used, inefficient
calls to these methods might result in expensive and inefficient code.
Fix
To fix this issue, call the std::string methods by using single
quoted characters instead of a string literal when appropriate. For instance, you might use
a single quoted character as an input instead of a string literal consisting of a single
character or a repetition of a single character. You might need to use a different overload
of the method that accepts a single quoted character.
Performance improvements might vary based on the compiler, library implementation, and environment that you are using.
Examples
Result Information
| Group: Performance |
| Language: C++ |
| Default: Off |
Command-Line Syntax:
EXPENSIVE_USE_OF_STD_STRING_METHODS |
| Impact: Low |
Version History
Introduced in R2021a
See Also
Topics
- Interpret Bug Finder Results in Polyspace Desktop User Interface
- Interpret Bug Finder Results in Polyspace Access Web Interface (Polyspace Access)
- Address Results in Polyspace User Interface Through Bug Fixes or Justifications
- Address Results in Polyspace Access Through Bug Fixes or Justifications (Polyspace Access)