Possible Duplicate:
is “else if” faster than “switch() case” ?
I’ve encountered a lot of situations lately where I have very simple conditionals and need to branch application flow. The “simplest” means of accomplishing what I’m doing is just a plain old if/elseif statement:
if($value == "foo") {
// ...
} elseif($value == "bar") {
// ...
} elseif($value == "asdf" || $value == "qwerty") {
// ...
}
…but I’m also considering something like:
switch($value) {
case "foo":
// ...
break;
case "bar":
// ...
break;
case "qwer":
case "asdf":
// ...
}
This seems a little less readable, but perhaps it’s more performant? However, when there are more and more “or” expressions in the conditional, it seems that the switch statement is much more readable and useful:
switch($value) {
case "foo":
// ...
break;
case "bar":
case "baz":
case "sup":
// ...
break;
case "abc":
case "def":
case "ghi":
// ...
break;
case "qwer":
case "asdf":
// ...
}
I’ve also seen options where code flow is branched using arrays and functions:
function branch_xyz() {/* ... */}
function branch_abc() {/* ... */}
function branch_def() {/* ... */}
$branches = array(
"xyz"=>"branch_xyz",
"abc"=>"branch_abc",
"def"=>"branch_def"
);
if(isset($branches[$value])) {
$fname = $branches[$value];
$fname();
}
This last option also presumably has the benefit of being distributable across multiple files, though it is pretty ugly.
Which do you feel has the most advantages with the fewest tradeoffs in terms of performance, readability, and ease of use?
Personally, I find the switch a lot more readable. Here’s the reason:
Condensed like that, you can easily see the trip up (be it a typo, or a honest difference). But with a switch, you know implicitly what was meant:
Plus, which is easier to read:
or
From a performance standpoint… Well, don’t worry about the performance. Unless you’re doing a few thousand of them inside of a tight loop, you won’t even be able to tell the difference (the difference will likely be in the micro-second range, if not lower).
Go for the method that you find the most readable. That’s the important part. Don’t try to micro-optimize. Remember,
Premature Optimization Is The Root Of All Evil…