Monday 11th December 2006
While benchmarking code for
CopperOnion I discovered that several routines seemed to run slower than I was expecting. On further investigation I noticed they all used recursion, a function calling it's self, as part of their functionality. So in a quest to find an efficient looping mechanism I created the following comparison test.
====Running 1000 Loop Tests====
FUNCTION 0.04176 seconds
FOR 0.01718 seconds
WHILE 0.01474 seconds
FOREACH 0.00967 seconds
As you can see PHP5 does not cope well with recursive function calls, upsetting. However my personal favorite 'foreach' looks like a clear winner in the looping finials, running almost twice as fast as a 'for' loop. The test code used is listed below for your interest.
function loop( $total=0, $count=0 )
{
if($count>=LOOP_COUNT) return $total;
return loop( $count * 10 + $total, $count+1 );
}
for($i=0;$i
while($count
foreach(range(0,LOOP_COUNT-1) as $i)
{
$total = $i * 10 + $total;
}
So in conclusion 'foreach' should be your first choice for looping exploits in PHP5, and as nice as they are, recursive functions should only be used if all else fails.