Expensive use of substr()
to shorten a
std::string
The method std::string::substr()
is called to shorten an
std::string
object
Since R2022a
Description
This defect occurs when you call std::string::substr()
to shorten an
std::string
up to the nth
character:
std::string str; str = str.substr(0, n); ;//Defect
Risk
When you call std::string::substr()
to shorten or truncate a string,
the compiler first constructs a temporary string containing the smaller substring, and then
assigns the temporary string object to the original string. Shortening a string by calling
std::string::substr()
requires constructing a temporary string, which
is unnecessary. This method results in inefficient code.
Fix
Instead of calling std::string::substr()
, use
std::string::resize()
to shorten a string. When you shorten strings by
using the method std::string::resize()
, the end of the string is moved to
the location that you want without requiring any additional construction. The method
std::string::resize()
is more efficient than
std::string::substr()
for shortening strings.
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_STD_STRING_RESIZE |
Impact: Low |
Version History
Introduced in R2022a
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)