drupal_static normal vs advanced usage

Submitted by admin on Thu, 06/23/2011 - 21:21

f1 is slower than f2 by 1765.96% (17.7 times slower)

Full source code as executed.
define('LOOP', 200000);
 
function &drupal_static($name, $default_value = NULL, $reset = FALSE) {
  static $data = array(), $default = array();
  if (isset($data[$name]) || array_key_exists($name, $data)) {
    if ($reset) {
      $data[$name] = $default[$name];
    }
    return $data[$name];
  }
  if (isset($name)) {
    if ($reset) {
      return $data;
    }
    $default[$name] = $data[$name] = $default_value;
    return $data[$name];
  }
  foreach ($default as $name => $value) {
    $data[$name] = $value;
  }
  return $data;
}
function f1() {
  $foo = &drupal_static(__FUNCTION__);
  $foo = 17;
  for($i=0; $i<LOOP; ++$i) {
    $foo = &drupal_static(__FUNCTION__);
    $foo = &drupal_static(__FUNCTION__);
    $foo = &drupal_static(__FUNCTION__);
    $foo = &drupal_static(__FUNCTION__);
    $foo = &drupal_static(__FUNCTION__);
  }
}
function f2() {
  static $drupal_static_fast;
  $drupal_static_fast = &drupal_static(__FUNCTION__);
  $drupal_static_fast = 17;
  for($i=0; $i<LOOP; ++$i) {
    if(isset($drupal_static_fast)) $drupal_static_fast;
    if(isset($drupal_static_fast)) $drupal_static_fast;
    if(isset($drupal_static_fast)) $drupal_static_fast;
    if(isset($drupal_static_fast)) $drupal_static_fast;
    if(isset($drupal_static_fast)) $drupal_static_fast;
   }
}
$start = microtime(true);
f1();
$stop = microtime(true);
$time1 = $stop - $start;
 
$start = microtime(true);
f2();
$stop = microtime(true);
$time2 = $stop - $start;
 
echo $time1 . "\t";
echo $time2 . "\n";
Test results
comparisontime1time2php_version
1765.96%20835291116605.3.3-7+squeeze1
50%
updown
50%