Looping in any programming language is an absolutely fundamental tool. However, this same technique that makes our lives so much easier can also result in substantially slower code. For this illustration, consider a script that takes a string and creates a new shuffled version of that string. One solution to this problem is as follows:
Notice that in this solution the strlen() function is called for every iteration of the for loop. In this case, the value returned from strlen() is constant for this loop (invariant) and needs to be calculated only once. Method #2 removes the strlen() calculation from the loop itself by calculating the value once and storing the result in a variable:
When profiling these two methods against each other, we find the following results:
NOTE
For this particular code snippet, it is notable that the amount of time taken to execute the segment was so small that profiling information was inaccurate. To provide more accurate profiling information, both methods were executed 100 times.
Method one took 0.04446005821228 seconds. Method two took 0.035489916801453 seconds.