Skip to content

Instantly share code, notes, and snippets.

@technosophos
Created August 18, 2011 19:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save technosophos/d1fe59a23daa33aaf6fe to your computer and use it in GitHub Desktop.
Save technosophos/d1fe59a23daa33aaf6fe to your computer and use it in GitHub Desktop.
PHP Switch vs. If/Else
<?php
$iterations = 10000;
$options = array('apple', 'banana', 'carrot');
$color = NULL;
// Fill an array with random keys. This ensures
// that (a) we use the same keys, and (b)
// slowness in the randomizer doesn't impact the
// loops (which can happen if entropy collection kicks in)
$samples = array();
for ($i = 0; $i < $iterations; ++$i) {
$samples[] = $options[rand(0, 2)];
}
// Test a switch statement.
$start_switch = microtime(TRUE);
for ($i = 0; $i < $iterations; ++$i) {
$option = $samples[$i];
switch ($option) {
case 'apple':
$color = 'red';
break;
case 'banana':
$color = 'yellow';
break;
default:
$color = 'green';
}
}
$end_switch = microtime(TRUE);
$total_switch = $end_switch - $start_switch;
printf("Switch:\t%0.6f sec to process %d" . PHP_EOL, $total_switch, $iterations);
// Test an array lookup.
$start_map = microtime(TRUE);
for ($i = 0; $i < $iterations; ++$i) {
$option = $samples[$i];
if ('apple' == $option) {
$color = 'red';
}
elseif ('banana' == $option) {
$color = 'yellow';
}
else {
$color = 'green';
}
}
$end_map = microtime(TRUE);
$total_map = $end_map - $start_map;
printf("If:\t%0.6f sec to process %d" . PHP_EOL, $total_map, $iterations);
@iggyster
Copy link

iggyster commented Jan 4, 2019

This is the wrong test. Of course, the if statement will be faster in option with three compares. But, what will happen when you increase the number of cases for switch & if. My, solution shows another result. Try it by yourself on PHP 7.2

<?php

$bar = 'bar';
$start = microtime(true);

if ($bar === 'foo') {
    $foo = 'foo';
} elseif ($bar === 'var') {
    $foo = 'var';
} elseif ($bar === 'let') {
    $foo = 'let';
} elseif ($bar === 'net') {
    $foo = 'net';
} else {
    $foo = 'bar';
}

$end = microtime(true);
printf('If: %0.6f sec to process' . PHP_EOL, $end - $start);

$start = microtime(true);

switch ($bar) {
    case 'foo':
        $foo = 'foo';
        break;
    case 'var':
        $foo = 'var';
        break;
    case 'let':
        $foo = 'let';
        break;
    case 'net':
        $foo = 'net';
        break;
    default:
        $foo = 'bar';
        break;
}

$end = microtime(true);
printf('Switch: %0.6f sec to process' . PHP_EOL, $end - $start);

I think to be sure for 100% you need to run both these tests in separated scripts.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment