Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

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

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
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.