drupal_static normal vs advanced usage

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

f1 is slower than f2 by 1615.29% (16.2 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
1496.67%36361022773php-5.3.6-phpbrew_compiled
1515.37%37066322946php-5.3.7-phpbrew_compiled
1463.85%36606523408php-5.3.8-phpbrew_compiled
1390.37%38198325630php-5.3.9-phpbrew_compiled
1670.14%40136122674php-5.3.10-phpbrew_compiled
1509.89%37191723102php-5.3.11-phpbrew_compiled
1514.11%36537022636php-5.3.12-phpbrew_compiled
1515.67%36722622729php-5.3.13-phpbrew_compiled
1422.14%35748923486php-5.3.14-phpbrew_compiled
1477.03%36180322942php-5.3.15-phpbrew_compiled
1463.53%36272323199php-5.3.16-phpbrew_compiled
1517.95%36754922717php-5.3.17-phpbrew_compiled
1288.6%35949425889php-5.3.18-phpbrew_compiled
1525.98%37265922919php-5.3.19-phpbrew_compiled
1777.99%30218716091php-5.4.0-phpbrew_compiled
2050.55%34688316130php-5.4.1-phpbrew_compiled
1805.62%30703316112php-5.4.2-phpbrew_compiled
2053.26%36177016801php-5.4.3-phpbrew_compiled
1745.68%30116016317php-5.4.4-phpbrew_compiled
1588.48%30433218024php-5.4.5-phpbrew_compiled
1626.34%30697717782php-5.4.6-phpbrew_compiled
1847.44%30888315861php-5.4.7-phpbrew_compiled
1832.37%30910215996php-5.4.8-phpbrew_compiled
1517.26%30522618873php-5.4.9-phpbrew_compiled
50%
updown
50%