Main Content

Inefficient string length computation

String length calculated by using string length functions on return from std::basic_string::c_str() instead of using std::basic_string::length()

Since R2020a

Description

This defect occurs when the length of a std::basic_string string is calculated by using string length functions on the pointer returned from std::basic_string::c_str() instead of using the method std::basic_string::length().

The checker flags string length functions such as strlen, wcslen and char_traits::length.

Risk

std::basic_string::c_str() returns a pointer to a null-terminated character array that stores the same data as the data stored in the string. Using a string length function such as strlen on this character array is expected to return the string length. This approach might seem superficially equivalent to using the std::basic_string::length() method for the string length.

However, the function strlen(str) is of linear complexity O(N) where N is the length of string str. If str is of type std::basic_string, this complexity is unnecessary since calling the std::basic_string::length() method returns the length more efficiently (with complexity O(1)).

Fix

If a string is of type std::basic_string, to get the string length, instead of using string length functions such as strlen, for instance:

std::string s;
auto len = strlen(s.ctr());
use the std::basic_string::length() method, for instance:
std::string s;
auto len = s.length();

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

Result Information

Group: Performance
Language: C++
Default: Off
Command-Line Syntax: INEFFICIENT_BASIC_STRING_LENGTH
Impact: Medium

Version History

Introduced in R2020a