Search code examples
c++substr

Space complexity of str.substr() in C++


What is the space complexity of the str.substr() function and how does it compare to str.erase()?


Wondering because I was running a code on leetcode, and used 150MB of memory when I used the substr function:

num = num.substr(1,num.size());

As soon as I removed this function and instead used the erase function, while changing nothing else in my code, the memory usage fell to 6.8MB. Updated code with erase function:

num = num.erase(0,1);

Solution

  • num = num.substr(1,num.size());
    

    substr creates a copy of string without the first character, so out of the 1 character less after the call you have (almost) two times the initial string

    (1) the string are shared, so after the assignment the initial string is deleted if it is not referenced from elsewhere, but before the assignment you had the two versions in memory requiring memory.

    num = num.erase(0,1);
    

    modifies the string, so that need only one version of the string during the execution

    note it is the same as doing

    num.erase(0,1);
    

    (1): from Pete Becker remark since C++11 the internal representation of std::basic_string is explicitly not allowed to be shared