Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: C++
Expertise: All
May 31, 2000



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Cache the Result of Complex Computations

The following loop is very inefficient:

for (int j=0; j<strlen(s); ++j)
  //  .. do something

On each iteration, this loop invokes the function strlen() to evaluate its condition. This is highly inefficient because strlen() is CPU intense. Its execution time depends on the length of s. Is there a way to improve this loop's performance? Certainly. Instead of calling strlen() repeatedly, call it only once and cache the result for further calculations:

const int length = strlen(s); // cache the result
for (int j=0; j<length; ++j) // use cached value
  //  .. do something
Danny Kalev
Thanks for your registration, follow us on our social networks to keep up-to-date