Extended if vs short if

Submitted by Lito on Fri, 03/16/2012 - 15:31

f2 is slower than f1 by 7.11%

Full source code as executed.
/* How many times the code under test should run in each function */
define('LOOP',1000000);
 
function f1() {
  for($i=0; $i<LOOP; ++$i) {
    if ($_SERVER['HTTP_CLIENT_IP']) {
      $_SERVER['HTTP_CLIENT_IP'];
    } else if ($_SERVER['HTTP_X_FORWARDED_FOR']) {
      $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else {
      $_SERVER['REQUEST_TIME'];
    }
  }
}
function f2() {
  for($i=0; $i<LOOP; ++$i) {
    $_SERVER['HTTP_CLIENT_IP'] ?: $_SERVER['HTTP_X_FORWARDED_FOR'] ?: $_SERVER['REQUEST_TIME'];
  }
}
$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
1.36%824978083617165.3.3-7+squeeze1
14.07%595708679516php-5.3.6-phpbrew_compiled
8.96%610381665069php-5.3.7-phpbrew_compiled
8.05%596296644294php-5.3.8-phpbrew_compiled
7.57%605189651000php-5.3.9-phpbrew_compiled
9.97%587424645989php-5.3.10-phpbrew_compiled
8.75%613460667119php-5.3.11-phpbrew_compiled
8.73%617977671943php-5.3.12-phpbrew_compiled
8.49%619833672434php-5.3.13-phpbrew_compiled
12.28%598991672559php-5.3.14-phpbrew_compiled
8.29%605744655971php-5.3.15-phpbrew_compiled
10.14%604777666080php-5.3.16-phpbrew_compiled
4.16%631394657635php-5.3.17-phpbrew_compiled
13.97%629926717933php-5.3.18-phpbrew_compiled
8.59%624329677988php-5.3.19-phpbrew_compiled
4.49%551315576092php-5.4.0-phpbrew_compiled
3.93%576726599411php-5.4.1-phpbrew_compiled
1.29%612887605091php-5.4.2-phpbrew_compiled
3.6%614149636252php-5.4.3-phpbrew_compiled
9.35%534368584308php-5.4.4-phpbrew_compiled
6.28%536096569743php-5.4.5-phpbrew_compiled
2.76%553230568517php-5.4.6-phpbrew_compiled
4.72%527808552722php-5.4.7-phpbrew_compiled
4.61%529103553518php-5.4.8-phpbrew_compiled
5.96%556125589285php-5.4.9-phpbrew_compiled
50%
updown
50%

Comments

Submitted by Hani on Sat, 03/24/2012 - 20:03

The comparison above is really comparing if + empty() function vs just if as opposed to what is in the title: extended vs short if.
I think it shuld be re-written without the empty() funciton in f1(). I did quick test - as it is f2() is about 3 times slower but after removing empty() from f1() the times are nearly identical - which is what I would expect.