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?