PHP tip: Do not use functions in end condition of for loop
Function, which is called inside the loop is executed always in each iteration.
A lot of programmers use function calls inside the loop, even though it is useless. In some cases it is this necessary, but many programmers use this procedure unnecessarily.
We can look to bad use a for loop:
Objective-C
1 2 3 4 5 6 7 8 9 10 11 |
//create empty string $str = ''; //create long string for( $i = 0; $i < 1000000; $i++){ $str.= $i; } //use function inside loop for($i = 0; $i < strlen($str); $i++){ $i%2; //somethig } |
The execution time of this example is: 1.45 seconds
Now we change the example on the following code:
Objective-C
1 2 3 4 5 6 7 8 9 10 11 12 13 |
//create empty string $str = ''; //create long string for( $i = 0; $i < 1000000; $i++){ $str.= $i; } //calculate lenght of this string $len = strlen($str); //use length in loop for($i = 0; $i < $len; $i++){ $i%2; //somethig } |
The execution time of this example is: 0.48 seconds
This procedure is not available always, for example, if we adjust the variable inside the loop, but it is possible to save CPU time.
Posted on 26 August 2013
I think, that article has a bad title. It should be – Do not use functions in end condition of for loop. Because your title advise me – do not use functions inside for loop at all:)
Thank you, you’re right, I modified the title of an article