[TYPO3-dev] FYI: comparing execution speed of some php functions

Jigal van Hemert jigal at xs4all.nl
Fri Jun 26 23:44:37 CEST 2009


Hi Rupert,

Rupert Germann wrote:
> for() loop using count() took           20.86401 ms 
> for() loop Not using count() took       7.09796 ms
> 
> using count() means: 
> for ($i = 1; $i < count($myarr); ++ $i) {...

What does not using count() mean?
If it's:
for($i = 1, $c = count($myarr); $i < $c; ++ $i) {...

These are functionally different AFAIK.

If the array grows when the for-loop is executed then count() is updated
in the first loop and not updated in the second loop.

See:
http://www.php.net/manual/en/control-structures.for.php

> foreach() loop:
> ---------------------------------------------
> foreach() took                  11.16920 ms
> foreach() with KEY took         12.35318 ms
> 
> while(list()=each()) loop:
> ---------------------------------------------
> while(list()...) took           58.12597 ms
> while(list()...) with key took  64.06283 ms

There is another difference between these two, see:
http://www.php.net/manual/en/control-structures.foreach.php

Quote: "Note: Unless the array is referenced, foreach operates on a copy
of the specified array and not the array itself. foreach  has some side
effects on the array pointer. Don't rely on the array pointer during or
after the foreach without resetting it. "

If you have to process a really big array foreach() will make a copy of
the array (unless you reference it) and you can easily run out of memory.

> foreach($arr as $key => $val) {
>   // do smthg that needs only $key
> }

So, this should be:

foreach($arr as $key => &$val) {
   //or foreach(&$arr as $key => $val) { ????
   // do smthg that needs only $key
}

> function arraytest2($num) {
>         $testvar = $GLOBALS['foo']['bar'];
>         for ($i = 0; $i < $num; ++ $i) {
>                 if ($testvar == "test") {
>                         $j = 1;
>                 } else {
>                         $j = FALSE;
>                 }
>         }
> }

I assume this has more to do with accessing an array member than 
accessing a global variable.

What is the speed of this:

function arraytest2($num) {
         $testvar = $GLOBALS;
         for ($i = 0; $i < $num; ++ $i) {
                 if ($testvar['foo']['bar'] == "test") {
                         $j = 1;
                 } else {
                         $j = FALSE;
                 }
         }
}

Thanks for starting an interesting thread!

-- 
Jigal van Hemert.




More information about the TYPO3-dev mailing list