en general la excusa que se da es que usando switch en determinados casos es más elegante (para los estilistas del código), pero la verdad pura y simple es que switch es más rápido.
un test al respecto (en javascript) disponible en:
http://home.earthlink.net/~kendrasg/...jsOptMain.html
repitiendo 2 bloques de codigo que hacen exactamente lo mismo, toma el tiempo que tarda en hacerlo 100.000 veces tanto el if como el switch.
En todos los navegadores que lo probe, el ganador fue switch:
Internet Explorer: IF: 651ms Switch: 421ms
Mozilla: IF: 681ms Switch: 80ms (si! ochenta!!)
Opera: IF: 3465ms Switch: 1382ms
Con lo que se ve a las claras que lo más optimo es usar Switch. Ademas de ver que el Mozilla parece tener el engine de JavaScript más rápido y el Opera parece tener un javascript MUY lento.
Después de ver esa página hice mis propios tests en php:
Código PHP:
<?php
function microtime_diff($a, $b) {
list($a_dec, $a_sec) = explode(" ", $a);
list($b_dec, $b_sec) = explode(" ", $b);
return $b_sec - $a_sec + $b_dec - $a_dec;
}
function ejecutarIf() {
$x=20;
$y=0;
for ($i=0; $i < 100000000; $i++) {
if ($x==1) {$y = $x;}
else if($x==2) {$y=$x;}
else if($x==3) {$y=$x;}
else if($x==4) {$y=$x;}
else if($x==5) {$y=$x;}
else if($x==6) {$y=$x;}
else if($x==7) {$y=$x;}
else if($x==8) {$y=$x;}
else if($x==9) {$y=$x;}
else if($x==10) {$y=$x;}
else if($x==11) {$y=$x;}
else if($x==12) {$y=$x;}
else if($x==13) {$y=$x;}
else if($x==14) {$y=$x;}
else if($x==15) {$y=$x;}
else if($x==16) {$y=$x;}
else if($x==17) {$y=$x;}
else if($x==18) {$y=$x;}
else if($x==19) {$y=$x;}
else if($x==20) {$y=$x;}
}
}
function ejecutarSwitch() {
$x=20;
$y=0;
for ($i=0; $i < 100000000; $i++) {
switch ($x) {
case 1 : $y=$x;break;
case 2 : $y=$x;break;
case 3 : $y=$x;break;
case 4 : $y=$x;break;
case 5 : $y=$x;break;
case 6 : $y=$x;break;
case 7 : $y=$x;break;
case 8 : $y=$x;break;
case 9 : $y=$x;break;
case 10 : $y=$x;break;
case 11 : $y=$x;break;
case 12 : $y=$x;break;
case 13 : $y=$x;break;
case 14 : $y=$x;break;
case 15 : $y=$x;break;
case 16 : $y=$x;break;
case 17 : $y=$x;break;
case 18 : $y=$x;break;
case 19 : $y=$x;break;
case 20 : $y=$x;
}
}
}
echo "<b>Tiempos</b>:<br><br>\n";
$empezoIF = microtime();
ejecutarIF();
$lapsoIf = microtime_diff($empezoIF, microtime());
printf("IF: %0.3f segundos<br>\n", $lapsoIf);
$empezoSwitch = microtime();
ejecutarSwitch();
$lapsoSwitch = microtime_diff($empezoSwitch, microtime());
printf("SWITCH: %0.3f segundos<br>\n", $lapsoSwitch);
?>