Don't use strlen in a loop condition.

This tip submitted by anonytmouse on 2005-02-10 20:34:50. It has been viewed 74662 times.
Rating of 7.4 with 342 votes



The strlen function is expensive. For every call it must loop over every character in the input string until a nul terminator is found. Therefore, it is very unwise to call it more often than needed. This is bad code:
for ( int ix = 0; ix < strlen(a_str); ix++)
{
     a_str[ix] = tolower( (unsigned char) a_str[ix] );
}

Lets consider a string 1000 characters in length. strlen will be called 1001 times and loop over 1000 characters each time. That is over one million wasted iterations. If the tolower call and assignment takes the equivalent of 10 iterations we can calculate that the operation takes one hundred times longer than it would if written correctly.

strlen as a loop condition should be replaced with:
for ( int ix = 0; a_str[ix] != '\0'; ix++)
{
     a_str[ix] = tolower( (unsigned char) a_str[ix] );
}

or the slightly less efficient:
int len = strlen(a_str);
for ( int ix = 0; ix < len; ix++)
{
     a_str[ix] = tolower( (unsigned char) a_str[ix] );
}

As well as removing unnecessary strlen calls from loops, you should try to remove any other expensive function calls.

You can read more on this issue in the thread, Just say NO to strlen.



More tips

Help your fellow programmers! Add a tip!