c++stringcompiler-optimizationloop-invariant

Is using string.length() in loop efficient?


For example, assuming a string s is this:

for(int x = 0; x < s.length(); x++)

better than this?:

int length = s.length();
for(int x = 0; x < length; x++)

Solution

  • In general, you should avoid function calls in the condition part of a loop, if the result does not change during the iteration.

    The canonical form is therefore:

    for (std::size_t x = 0, length = s.length(); x != length; ++x);
    

    Note 3 things here:

    (I also changed the type because is a negative length is non-sense and the string interface is defined in term of std::string::size_type, which is normally std::size_t on most implementations).

    Though... I admit that it's not as much for performance than for readability:

    In short: use the best tool for the job at hand :)