Many if statements faster then elseif
Posted: Wed May 30, 2007 5:54 pm
I was really surprised with this result.
I thought that with this code after the second elseif statement the rest of the elseif statements don't have to be evaluated and therefore faster that the second script.
But this is not the case.
Can someone explain why the second script is faster?
I thought that with this code after the second elseif statement the rest of the elseif statements don't have to be evaluated and therefore faster that the second script.
But this is not the case.
Can someone explain why the second script is faster?
Code: Select all
<?php
list($usec, $sec) = explode(' ', microtime());
$start_time = $usec + $sec;
$q = 2;
for ($i = 0; $i < 1000000; $i++)
{
if ($q == 1) {}
elseif ($q == 2) {}
elseif ($q == 3) {}
elseif ($q == 4) {}
elseif ($q == 5) {}
elseif ($q == 6) {}
elseif ($q == 7) {}
elseif ($q == {}
elseif ($q == 9) {}
}
list($usec, $sec) = explode(' ', microtime());
$execution_time = $usec + $sec - $start_time;
echo 'Script execution time: ' . number_format($execution_time * 1000, 1) . 'ms';
?>Code: Select all
<?php
list($usec, $sec) = explode(' ', microtime());
$start_time = $usec + $sec;
$q = 2;
for ($i = 0; $i < 1000000; $i++)
{
if ($q == 1) {}
if ($q == 2) {}
if ($q == 3) {}
if ($q == 4) {}
if ($q == 5) {}
if ($q == 6) {}
if ($q == 7) {}
if ($q == {}
if ($q == 9) {}
}
list($usec, $sec) = explode(' ', microtime());
$execution_time = $usec + $sec - $start_time;
echo 'Script execution time: ' . number_format($execution_time * 1000, 1) . 'ms';
?>