Main Content

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

expand all

#include<string>
void shortenString(std::string& str, size_t pos){
	str = str.substr(0, pos);//Defect
}

In this example, the substr() method is called to shorten the string str. This method creates a temporary string object containing the first pos characters of str, and then overwrites str with the temporary string. This method of shortening a string object is inefficient and Polyspace® flags it.

Correction — Use std::string::resize()

To resolve this defect, use the resize() method to shorten the string. This method does not create any new string objects and is more efficient.

#include<string>
void shortenString(std::string& str, size_t pos)
{
    if (pos < str.size()) {
        str.resize(pos);
    }
}

Result Information

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

Version History

Introduced in R2022a