Why strlen is avoided in a loop condition in C++?
Supriyo Ghosh
Marketing Manager | Performance Marketing | Brand Communication | Social Media Marketer | SEO Specialist | Content Strategist | SEO Expert
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.