fork download
  1. <?php
  2.  
  3. // Setup
  4. $start_time = NULL;
  5. $stop_time = NULL;
  6. $ELEMENTS = 1000000;
  7. $ITERATIONS = 10;
  8.  
  9. $arr = array_fill(0, $ELEMENTS, 10000);
  10. echo "Array size is $ELEMENTS.\n",
  11. "Each test ran $ITERATIONS times.\n\n";
  12.  
  13. // foreach
  14. $runtimes = array();
  15. for ($i = 0; $i < $ITERATIONS; $i++) {
  16. $start_time = microtime(true);
  17. foreach ($arr as $i => $elem);
  18. $stop_time = microtime(true);
  19. $runtimes[] = $stop_time - $start_time;
  20. }
  21. $average = array_sum($runtimes) / sizeof($runtimes);
  22. echo "foreach: " , $average , "\n";
  23.  
  24. // no key foreach
  25. $runtimes = array();
  26. for ($i = 0; $i < $ITERATIONS; $i++) {
  27. $start_time = microtime(true);
  28. foreach ($arr as $elem);
  29. $stop_time = microtime(true);
  30. $runtimes[] = $stop_time - $start_time;
  31. }
  32. $average = array_sum($runtimes) / sizeof($runtimes);
  33. echo "no key foreach: " , $average , "\n";
  34.  
  35. // not cached sizeof loop
  36. $runtimes = array();
  37. for ($i = 0; $i < $ITERATIONS; $i++) {
  38. $start_time = microtime(true);
  39. for ($i = 0; $i < sizeof($arr); $i++);
  40. $stop_time = microtime(true);
  41. $runtimes[] = $stop_time - $start_time;
  42. }
  43. $average = array_sum($runtimes) / sizeof($runtimes);
  44. echo "uncached for: " , $average , "\n";
  45.  
  46. // cached sizeof loop
  47. $runtimes = array();
  48. for ($i = 0; $i < $ITERATIONS; $i++) {
  49. $start_time = microtime(true);
  50. $sizeof_arr = sizeof($arr);
  51. for ($i = 0; $i < $sizeof_arr; $i++);
  52. $stop_time = microtime(true);
  53. $runtimes[] = $stop_time - $start_time;
  54. }
  55. $average = array_sum($runtimes) / sizeof($runtimes);
  56. echo "cached for: " , $average , "\n\n";
  57.  
  58.  
Success #stdin #stdout 2.12s 13112KB
stdin
Standard input is empty
stdout
Array size is 1000000.
Each test ran 10 times.

foreach: 0.163385152817
no key foreach: 0.122173881531
uncached for: 0.385900974274
cached for: 0.133785009384