Switch vs. Variable Functions in PHP
Is it possible that using switch statements to do a common PHP task is actually slower than using variable functions? I put it to the test and the results are surprising.
I started this research the way I usually do - by throwing some text at the search engines. A general consensus among the results returned was that it simply didn't matter. However one page suggested that the general consensus might be wrong.
Many times a switch is used to determine what function to call for a given variable's value. I suspected that this was inefficient, and that using variable functions would be faster, but I wanted to prove the difference in speed in actual code. I wrote two simple scripts that would each run a loop ten million times. One would use a switch and would examine the worst case scenario (matching case at the bottom of the switch block) and the other would use variable functions, assigning the name of the function to a variable each time the loop ran.
Here are the 2 scripts I used.
<?PHP
function something( $val )
{
// nothing here
}
function something_else( $val )
{
// nothing here
}
function tim( $val )
{
// nothing here
}
$val = 'tim';
$start = microtime( true );
for ( $ix = 0; $ix < 10000000; $ix++ )
{
switch ( $val )
{
case 'something':
something( 'test' );
break;
case 'something_else':
something_else( 'test' );
break;
case 'something_else1':
something_else( 'test' );
break;
case 'something_else2':
something_else( 'test' );
break;
case 'something_else3':
something_else( 'test' );
break;
case 'something_else4':
something_else( 'test' );
break;
case 'something_else5':
something_else( 'test' );
break;
case 'something_else6':
something_else( 'test' );
break;
case 'tim':
tim( '' );
break;
default:
echo 'default';
break;
}
}
$stop = microtime( true );
echo $stop-$start;
On my server, which is ubuntu running in a virtual machine on my mac, 10 million iterations took 12.9 seconds.
<?php
function tim( $val )
{
// nothing here
}
$start = microtime( true );
for ( $ix = 0; $ix < 10000000; $ix++ )
{
$func = 'tim';
$func( 'tim' );
}
$stop = microtime( true );
echo $stop-$start;
On the same server, this second test script took only 5.2 seconds.

I was staggered when I saw that.
I will admit that ten million iterations is a lot, and that, practically, 12 or 13 seconds for 10 million is insignificant per each, but the overall difference of being over twice as slow as using variable functions is staggering, and is changing the way I view switch statements. I'm not planning on re-factoring any code, but I will be taking these results into consideration when writing new code.
I hope this short article proves to be useful to you. Please email any comments to tim@tgwebsolutions.com - I'll post any interesting or useful ones on this page.
