Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
PHP Performance: if/elseif vs case/switch vs nested if
<?php
$iter = 500000;
$start = microtime(true);
$n = 0;
for ($c=0; $c<7*$iter; $c++) {
$i = $c % 16;
if ($i===0) $n += 0;
elseif ($i===1) $n -= 1;
elseif ($i===2) $n -= 2;
elseif ($i===3) $n += 3;
elseif ($i===4) $n += 4;
elseif ($i===5) $n -= 5;
elseif ($i===6) $n -= 6;
elseif ($i===7) $n += 7;
elseif ($i===8) $n += 0;
elseif ($i===9) $n -= 1;
elseif ($i===10) $n -= 2;
elseif ($i===11) $n += 3;
elseif ($i===12) $n += 4;
elseif ($i===13) $n -= 5;
elseif ($i===14) $n -= 6;
elseif ($i===15) $n += 7;
}
echo 'RESULT: ';
echo microtime(true) - $start. " (FLAT IF)\n";
// RESULT: 0.45587396621704 (FLAT IF)
$start = microtime(true);
$n = 0;
for ($c=0; $c<7*$iter; $c++) {
$i = $c % 16;
switch ($i) {
case 0:
$n += 0;
break;
case 1:
$n -= 1;
break;
case 2:
$n -= 2;
break;
case 3:
$n += 3;
break;
case 4:
$n += 4;
break;
case 5:
$n -= 5;
break;
case 6:
$n -= 6;
break;
case 7:
$n += 7;
break;
case 8:
$n += 0;
break;
case 9:
$n -= 1;
break;
case 10:
$n -= 2;
break;
case 11:
$n += 3;
break;
case 12:
$n += 4;
break;
case 13:
$n -= 5;
break;
case 14:
$n -= 6;
break;
case 15:
$n += 7;
break;
}
}
echo 'RESULT: ';
echo microtime(true) - $start. " (SWITCH CASE)\n";
// RESULT: 0.33157801628113 (SWITCH CASE)
$start = microtime(true);
$n = 0;
for ($c=0; $c<7*$iter; $c++) {
$i = $c % 16;
if ($i<8) {
if ($i < 4) {
if ($i < 2) {
if ($i===0) $n += 0;
else $n -= 1;
} else {
if ($i===2) $n -= 2;
else $n += 3;
}
} else {
if ($i < 6) {
if ($i===4) $n += 4;
else $n -= 5;
} else {
if ($i===6) $n -= 6;
else $n += 7;
}
}
} else {
if ($i < 12) {
if ($i < 10) {
if ($i===8) $n += 0;
else $n -= 1;
} else {
if ($i===10) $n -= 2;
else $n += 3;
}
} else {
if ($i < 14) {
if ($i===12) $n += 4;
else $n -= 5;
} else {
if ($i===14) $n -= 6;
else $n += 7;
}
}
}
}
echo 'RESULT: ';
echo microtime(true) - $start . " (NESTED IF)\n";
// RESULT: 0.25623297691345 (NESTED IF)
@Thalles

This comment has been minimized.

Copy link

@Thalles Thalles commented Apr 3, 2019

Add ifs

`$start = microtime(true);
$n = 0;
for ($c=0; $c<7*$iter; $c++) {
$i = $c % 16;

if ($i===0) $n += 0;
if ($i===1) $n -= 1;
if ($i===2) $n -= 2;
if ($i===3) $n += 3;
if ($i===4) $n += 4;
if ($i===5) $n -= 5;
if ($i===6) $n -= 6;
if ($i===7) $n += 7;
if ($i===8) $n += 0;
if ($i===9) $n -= 1;
if ($i===10) $n -= 2;
if ($i===11) $n += 3;
if ($i===12) $n += 4;
if ($i===13) $n -= 5;
if ($i===14) $n -= 6;
if ($i===15) $n += 7;

}
echo 'RESULT: ';
echo microtime(true) - $start. " (ONLY IF)\n";
// RESULT: 0.45587396621704 (ONLY IF).`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.