PHP5 array loop speedtest

April 10th, 2007 by William Yang

While searching for “php benchmark”, I found PHP Benchmark test page. The first benchmark the page showed was foreach(), while(list()=each()) and loop using array_keys(). The test result was stated as “strange”. Loop using array_keys() function out performed the other loop techniques by 2 to 9 folds. Of cause, the test was done in a PHP4 enviroment. Since PHP5 was introduced, there has been a lot of performance increases, the test is out dated.

Eagerly wanting to know how this will perform in PHP5, I have written a set of similar tests to be tested on my PHP5+Windows machine. The result is as expected: completely different, loop using array_keys() is no longer the best performed loop in PHP5.

The test array is made randomly generated 8 characters long string keys and 64 characters long string values.

Test results:

Loop style Test 1 Test 2 Test 3 Test 4 Test 5 Average
ForEachLoop 0.92 0.79 0.70 0.96 0.75 0.82
WhileListEachLoop 2.25 2.10 4.87 2.83 2.11 2.83
ForEachLoopWithKey 1.02 0.98 0.86 0.84 1.03 0.95
WhileListEachLoopWithKey 2.20 2.67 2.13 3.62 2.17 2.56
GetKeyLoop 3.76 6.00 3.30 3.24 4.26 4.11

PHP5 Loop test result

Source code:

Loop 1: foreach() loop without fetching array key

Show Code

  1.   foreach ($test_array as $ele) {
  2.     $tmp[] = $ele;
  3.   }

Loop 2: while(list()=each()) loop without fetching array key

Show Code

  1.   while (list(, $ele) = each($test_array)) {
  2.     $tmp[] = $ele;
  3.   }

Loop 3: foreach() loop fetching array key

Show Code

  1.   foreach ($test_array as $k=>$ele) {
  2.     $tmp[] = $ele;
  3.   }

Loop 4: while(list()=each()) loop fetching array key

Show Code

  1.   while (list($k, $ele) = each($test_array)) {
  2.     $tmp[] = $ele;
  3.   }

Loop 5: loop using array_keys()

Show Code

  1.   $keys = array_keys($test_array);
  2.   $count = sizeOf($keys);
  3.   for ($i=0; $i<$count; $i  ) {
  4.     $tmp[] = $test_array[$keys[$i]];
  5.   }

Full Source:

Show Code | Download looptest.txt

Leave a Reply