Search code examples
c++cdesign-principles

Computation of loop conditions


In a given loop eg:

for(int i=0 ; i < strlen(s) ; i++){
    //do something
}

Is the strlen(s) calculated for every iteration of the loop? How do the C and C++ languages handle this? If this function call is going to be made for every iteration and we know beforehand that the result from the function will be constant, is it more efficient to store this value in a variable? eg.:

int length = strlen(s);
for(int i=0 ; i< length ; i++){
    //do something
}

Solution

  • Yes, strlen(s) will be evaluated on each iteration.

    If you won't be changing the string in the loop, it is better (faster) to store the value in and then include it in the for loop.

    Fastest way to do this is:

    for(int i=0, length = strlen(s) ; i< length ; i++){
        //do something
    }