switch vs if ... else if ...

Submitted by tomek on Sun, 05/08/2011 - 13:53

f2 is slower than f1 by 9.42%

Full source code as executed.
define('LOOP',10000000);
function f1() {
  $a = "test 123";
  for($i=0; $i<LOOP; ++$i) {
    if($a == "one") {
    } elseif($a == "two") {
    } elseif($a == "three") {
    } else {
    }
  }
}
 
function f2() {
  $a = "test 123";
  for($i=0; $i<LOOP; ++$i) {
    switch($a) {
      case "one":
        break;
      case "two":
        break;
      case "three":
        break;
      default:
        break;
    }
  }
}
 
$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
11.69%844079494273765.3.5-1ubuntu7.2
23.41%705792587103085.3.3-7
12.79%11320507127687115.3.5-1ubuntu7.2
20.73%736505988917885.3.3-7+squeeze1
9.59%13385071466917php-5.3.6-phpbrew_compiled
8.21%14009891516055php-5.3.7-phpbrew_compiled
7.85%13631471470163php-5.3.8-phpbrew_compiled
11.28%13451741496881php-5.3.9-phpbrew_compiled
8.81%13825631504381php-5.3.10-phpbrew_compiled
9.36%13875901517480php-5.3.11-phpbrew_compiled
9.27%13890261517740php-5.3.12-phpbrew_compiled
9.38%13875651517668php-5.3.13-phpbrew_compiled
8.7%13623441480914php-5.3.14-phpbrew_compiled
10.6%13819931528441php-5.3.15-phpbrew_compiled
9.35%13660001493726php-5.3.16-phpbrew_compiled
11.08%13355501483558php-5.3.17-phpbrew_compiled
14.17%14611111668139php-5.3.18-phpbrew_compiled
11.69%13453561502642php-5.3.19-phpbrew_compiled
9.92%10858941193662php-5.4.0-phpbrew_compiled
0.73%13134421323031php-5.4.1-phpbrew_compiled
0.94%13676671380506php-5.4.2-phpbrew_compiled
0.99%13168041329800php-5.4.3-phpbrew_compiled
6.72%11135911188403php-5.4.4-phpbrew_compiled
5.46%11396901201867php-5.4.5-phpbrew_compiled
11.96%11076381240161php-5.4.6-phpbrew_compiled
7.21%10926091171347php-5.4.7-phpbrew_compiled
7.04%10829841159193php-5.4.8-phpbrew_compiled
4.69%12319241289739php-5.4.9-phpbrew_compiled
50%
updown
50%