Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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++)

Thanks, Joel

like image 777
Joel Avatar asked Feb 27 '11 19:02

Joel


3 Answers

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:

  • The initialization can initialize more than one variable
  • The condition is expressed with != rather than <
  • I use pre-increment rather than post-increment

(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:

  • The double initialization means that both x and length scope is as tight as necessary
  • By memoizing the result the reader is not left in the doubt of whether or not the length may vary during iteration
  • Using pre-increment is usually better when you do not need to create a temporary with the "old" value

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

like image 141
Matthieu M. Avatar answered Sep 30 '22 12:09

Matthieu M.


It depends on the inlining and optimization abilities of the compiler. Generally, the second variant will most likely be faster (better: it will be either faster or as fast as the first snippet, but almost never slower).

However, in most cases it doesn't matter, so people tend to prefer the first variant for its shortness.

like image 33
Alexander Gessler Avatar answered Sep 30 '22 10:09

Alexander Gessler


It depends on your C++ implementation / library, the only way to be sure is to benchmark it. However, it's effectively certain that the second version will never be slower than the first, so if you don't modify the string within the loop it's a sensible optimisation to make.

like image 31
Tim Martin Avatar answered Sep 30 '22 10:09

Tim Martin