V814. Decreased performance. The 'strlen' function was called multiple times inside the body of a loop

12.08.2013

The analyzer has detected a construct which can be optimized. Each loop's iteration calls the function strlen(S) or other similar function. The string 'S' is not changed; therefore, its length can be calculated beforehand. Sometimes you may get a significant performance boost due to this optimization.

Example 1.

for (;;) {
{
  ....
  segment = next_segment + strlen("]]>");
  ....
}

The length of the "]]>" string is being calculated multiple times in the loop. Though the string is short and the function strlen() works fast, you risk getting a slow-down for no obvious reason if the loop iterates millions of times. You can fix the defect in the following way:

const size_t suffixLen = strlen("]]>");
for (;;) {
{
  ....
  segment = next_segment + suffixLen;
  ....
}

Or rather use a macro like this:

#define LiteralStrLen(S) (sizeof(S) / sizeof(S[0]) - 1)
....
segment = next_segment + LiteralStrLen("]]>");

If you work with C++, create a templated function:

template <typename T, size_t N>
char (&ArraySizeHelper(T (&array)[N]))[N];

template <typename T, size_t N>
size_t LiteralStrLen(T (&array)[N]) {
  return sizeof(ArraySizeHelper(array)) - 1;
}
....
segment = next_segment + LiteralStrLen("]]>");

Example 2.

for(j=0; j<(int)lstrlen(text); j++)
{
  if(text[j]=='\n')
  {
    lines++;
  }
}

This code fragment counts the number of lines in a text and is taken from one real application.

If the text is large enough, the algorithm becomes quite inefficient. With each loop iteration, the program calculates the text length to compare it to the variable 'j'.

This is the optimized code:

const int textLen = lstrlen(text);
for(j=0; j<textLen; j++)
{
  if(text[j]=='\n')
  {
    lines++;
  }
}