note 13463 modified in control-structures.for by danbrown

From: Date: Mon, 07 Dec 2009 16:09:53 +0000
Subject: note 13463 modified in control-structures.for by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-163665@lists.php.net to get a copy of this message
The point about the speed in loops is, that the middle and the last expression are executed EVERY time it loops. So you should try to take everything that doesn't change out of the loop. Often you use a function to check the maximum of times it should loop. Like here: <?php for ($i = 0; $i <= somewhat_calcMax(); $i++) { somewhat_doSomethingWith($i); } ?> Faster would be: <?php $maxI = somewhat_calcMax(); for ($i = 0; $i <= $maxI; $i++) { somewhat_doSomethingWith($i); } ?> And here a little trick: <?php $maxI = somewhat_calcMax(); for ($i = 0; $i <= $maxI; somewhat_doSomethingWith($i++)) ; ?> The $i gets changed after the copy for the function (post-increment). --was-- The point about the speed in loops is, that the middle and the last expression are executed EVERY time it loops. So you should try to take everything that doesn't change out of the loop. Often you use a function to check the maximum of times it should loop. Like here: for ($i = 0; $i <= somewhat_calcMax(); $i++) { somewhat_doSomethingWith($i); } Faster would be: $maxI = somewhat_calcMax(); for ($i = 0; $i <= $maxI; $i++) { somewhat_doSomethingWith($i); } And here a little trick: $maxI = somewhat_calcMax(); for ($i = 0; $i <= $maxI; somewhat_doSomethingWith($i++)) ; The $i gets changed after the copy for the function (post-increment). I don't know if for ($i = 0; $i <= $maxI; somewhat_doSomethingWith($i), $i++) ; is correct...at least it's not really clear. http://php.net/manual/en/control-structures.for.php

« previous php.notes (#163665) next »