Advertisement
Guest User

FOR vs FOREACH

a guest
Aug 7th, 2010
3,155
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.   ## preperations; just a simple environment state
  2.  
  3.   $test_iterations = 100;
  4.   $test_arr_size = 1000;
  5.  
  6.   // a shared function that makes use of the loop; this should
  7.   // ensure no funny bussiness is happening to fool the test
  8.   function test($input)
  9.   {
  10.     echo '<!-- '.trim($input).' -->';
  11.   }
  12.  
  13.   // for each test we create a array this should avoid any of the
  14.   // arrays internal representation or optimizations from getting
  15.   // in the way.
  16.  
  17.   // normal array
  18.   $test_arr1 = array();
  19.   $test_arr2 = array();
  20.   $test_arr3 = array();
  21.   // hash tables
  22.   $test_arr4 = array();
  23.   $test_arr5 = array();
  24.  
  25.   for ($i = 0; $i < $test_arr_size; ++$i)
  26.   {
  27.     mt_srand();
  28.     $hash = md5(mt_rand());
  29.     $key = substr($hash, 0, 5).$i;
  30.    
  31.     $test_arr1[$i] = $test_arr2[$i] = $test_arr3[$i] = $test_arr4[$key] = $test_arr5[$key]
  32.       = $hash;
  33.   }
  34.  
  35.   ## foreach
  36.  
  37.   $start = microtime(true);
  38.   for ($j = 0; $j < $test_iterations; ++$j)
  39.   {
  40.     foreach ($test_arr1 as $k => $v)
  41.     {
  42.       test($v);
  43.     }
  44.   }
  45.   echo '<strong>foreach</strong> '.(microtime(true) - $start).'<br />';  
  46.  
  47.   ## foreach (using reference)
  48.  
  49.   $start = microtime(true);
  50.   for ($j = 0; $j < $test_iterations; ++$j)
  51.   {
  52.     foreach ($test_arr2 as &$value)
  53.     {
  54.       test($value);
  55.     }
  56.   }
  57.   echo '<strong>foreach</strong> (using reference) '.(microtime(true) - $start).'<br />';
  58.  
  59.   ## for
  60.  
  61.   $start = microtime(true);
  62.   for ($j = 0; $j < $test_iterations; ++$j)
  63.   {
  64.     $size = count($test_arr3);
  65.     for ($i = 0; $i < $size; ++$i)
  66.     {
  67.       test($test_arr3[$i]);
  68.     }
  69.   }
  70.   echo '<strong>for</strong> '.(microtime(true) - $start).'<br />';  
  71.  
  72.   ## foreach (hash table)
  73.  
  74.   $start = microtime(true);
  75.   for ($j = 0; $j < $test_iterations; ++$j)
  76.   {
  77.     foreach ($test_arr4 as $k => $v)
  78.     {
  79.       test($v);
  80.     }
  81.   }
  82.   echo '<strong>foreach</strong> (hash table) '.(microtime(true) - $start).'<br />';
  83.  
  84.   ## for (hash table)
  85.  
  86.   $start = microtime(true);
  87.   for ($j = 0; $j < $test_iterations; ++$j)
  88.   {
  89.     $keys = array_keys($test_arr5);
  90.     $size = sizeOf($test_arr5);
  91.     for ($i = 0; $i < $size; ++$i)
  92.     {
  93.       test($test_arr5[$keys[$i]]);
  94.     }
  95.   }
  96.   echo '<strong>for</strong> (hash table) '.(microtime(true) - $start).'<br />';
Advertisement
RAW Paste Data Copied
Advertisement