I think we all always have to do some dealings in conditions with few values.
I made a test between IF
and SWITCH
.
All content was created for SIMULAR a more identical structure possible between
IF
andSWITCH
.
Class file: ifXswitch.php
<?php
class Teste {
public function fc_if($v) {
// Marcador de tempo 1
$t1 = microtime(true);
// Script
if ($v == 1) { echo '<br>' . $v . ' elevado a 9 = ' . $this -> calcula(1); }
elseif ($v == 2) { echo '<br>' . $v . ' elevado a 9 = ' . $this -> calcula(2); }
elseif ($v == 3) { echo '<br>' . $v . ' elevado a 9 = ' . $this -> calcula(3); }
elseif ($v == 4) { echo '<br>' . $v . ' elevado a 9 = ' . $this -> calcula(4); }
elseif ($v == 5) { echo '<br>' . $v . ' elevado a 9 = ' . $this -> calcula(5); }
elseif ($v == 6) { echo '<br>' . $v . ' elevado a 9 = ' . $this -> calcula(6); }
elseif ($v == 7) { echo '<br>' . $v . ' elevado a 9 = ' . $this -> calcula(7); }
elseif ($v == 8) { echo '<br>' . $v . ' elevado a 9 = ' . $this -> calcula(8); }
elseif ($v == 9) { echo '<br>' . $v . ' elevado a 9 = ' . $this -> calcula(9); }
else { echo 'Número inválido'; }
// Marcador de tempo 2
$t2 = microtime(true);
// Tempo final
$t3 = $t2 - $t1;
return $t3;
}
public function fc_switch($v) {
// Marcador de tempo 1
$t1 = microtime(true);
// Script
switch ($v) {
case '1':
echo '<br>' . $v . ' elevado a 9 = ' . $this -> calcula(1);
break;
case '2':
echo '<br>' . $v . ' elevado a 9 = ' . $this -> calcula(2);
break;
case '3':
echo '<br>' . $v . ' elevado a 9 = ' . $this -> calcula(3);
break;
case '4':
echo '<br>' . $v . ' elevado a 9 = ' . $this -> calcula(4);
break;
case '5':
echo '<br>' . $v . ' elevado a 9 = ' . $this -> calcula(5);
break;
case '6':
echo '<br>' . $v . ' elevado a 9 = ' . $this -> calcula(6);
break;
case '7':
echo '<br>' . $v . ' elevado a 9 = ' . $this -> calcula(7);
break;
case '8':
echo '<br>' . $v . ' elevado a 9 = ' . $this -> calcula(8);
break;
case '9':
echo '<br>' . $v . ' elevado a 9 = ' . $this -> calcula(9);
break;
default:
echo 'Número inválido';
break;
}
// Marcador de tempo 2
$t2 = microtime(true);
// Tempo final
$t3 = $t2 - $t1;
return $t3;
}
public function calcula($v) {
$vf = pow($v,5);
sleep(1);
return $vf;
}
public function resultado($t_if, $t_switch) {
echo '<hr>';
echo '<br> Tempo IF: ' . $t_if;
echo '<br> Tempo SWITCH: ' . $t_switch;
if ($t_if < $t_switch) $r = 'IF';
elseif ($t_if == $t_switch) $r = 'Empate';
elseif ($t_if > $t_switch) $r = 'SWITCH';
else $r = 'Erro';
echo '<br> Menor tempo: ' . $r;
}
}
?>
Executor: mitrotime.php
<?php
include_once 'ifXswitch.php';
$exemplo = new Teste();
$t_if = $exemplo -> fc_if(9);
$t_switch = $exemplo -> fc_switch(9);
$exemplo -> resultado($t_if, $t_switch);
?>
In the test run, it varies a lot, time wins the IF time the SWITCH, and even unbelievably gave a tie once.
I would like to know, among them, if one has an advantage over the other in some aspect (eg with SWITCH numbers would be better!?), or is it about necessity and organization?