Public feed #893935

Unnamed

public php v1 · immutable
Raw Edit
·published 2008-02-06 15:47 UTC
rendered paste body
Size 10........Did method1 in 6.19888305664E-5 secondsDid method2 in 2.88486480713E-5 secondsDid method3 in 2.21729278564E-5 secondsSize 100........Did method1 in 0.0035548210144 secondsDid method2 in 0.00107884407043 secondsDid method3 in 0.000940084457397 secondsSize 1000........Did method1 in 0.295642137527 secondsDid method2 in 0.194920063019 secondsDid method3 in 0.0819511413574 secondsSize 10000........Did method1 in 36.8213510513 secondsDid method2 in 84.960575819 secondsDid method3 in 14.9312441349 seconds<?phpforeach(array(10, 100, 1000, 10000) as $size){  // allocate an array....  $myArray = array();  for($i = 0; $i < $size; ++$i)  {    $myArray[] = $i;  }  echo "Size {$size}........<br />";  // generate an array of indexs to test, we'll have size/2.....  $randomIndexes = array();  for ($i = 0; $i < $size/2; ++$i)  {    $randomIndexes[] = rand(0, $size-1);  }  $time_start = microtime(true);  foreach($randomIndexes as &$idx)  {    getByIndexMethod1($myArray, $idx);  }  $time_end = microtime(true);  $time = $time_end - $time_start;  echo "Did method1 in {$time} seconds<br />";  $time_start = microtime(true);  foreach($randomIndexes as &$idx)  {    getByIndexMethod2($myArray, $idx);  }  $time_end = microtime(true);  $time = $time_end - $time_start;  echo "Did method2 in {$time} seconds<br />";  $time_start = microtime(true);  foreach($randomIndexes as &$idx)  {    getByIndexMethod3($myArray, $idx);  }  $time_end = microtime(true);  $time = $time_end - $time_start;  echo "Did method3 in {$time} seconds<br /><hr />";  flush();}function getByIndexMethod1(&$array, $index){  reset($array);  $idx = 0;  $ret =& current($array);  do  {    if ($idx == $index)    {      return $ret;    }    ++$idx;  }  while ($ret =& next($array));  return false;}function getByIndexMethod2(&$array, $index){  $tmp = array_values($array);  if (isset($tmp[$index]))    return $tmp[$index];  return false;}function getByIndexMethod3(&$array, $index){  $i = 0;  foreach($array as $key => &$val)  {    if ($index == $i)      return $val;    $i++;  }  return false;}