Performance experiment: if / else vs. switch / case

at 2007-04-24 in Experiments by friebe (0 comments)

Starting from the following piece of code which is basically an excerpt from the remote.protocol.Serializer class:

<?php 
switch
(gettype($arg)) {
case
'integer': $r= 'INTEGER'; break;
case
'string': $r= 'STRING'; break;
case
'boolean': $r= 'BOOL'; break;
case
$arg instanceof Object: $r= 'OBJECT'; break;
}
?>

...I started wondering how fast that was, say, compared to if/else combination.

The alternatives that came to my head:

  • Use if/else
  • Use the ternary operator
  • Use a do/while(0) loop
The complete sourcecode can be seen in my experiments directory.

Comparison between the different methods:
Chart


Conclusion: The if/else combination is the fastest, followed by the ternary version (which is quite unreadable) and the do/while(0) and break combination - also kind of weird. While I personally think the switch statement is most readable, I had to learn it was also the slowest:(



Subscribe

You can subscribe to the XP framework's news by using RSS syndication.


Categories

News
General
PHP5
Announcements
RFCs
Further reading
Examples
Editorial
EASC
Experiments
Unittests
Databases

Related

Find related articles by a search for «Performance».