<?php
//copyright Lawrence Truett and FluffyCat.com 2009, all rights reserved
define('BR', "\n");
echo 'Performance Testing PHP if / else VS switch with 100,000 iterations'.BR.BR;
$ifTime = 0;
$switchTime = 0;
$arrayTime = 0;
for ($x = 0; $x < 100000; $x++) {
$oneToFive = rand(1,5);
if (0 == fmod($x,2)) {
$switchTime = $switchTime + testSwitch($oneToFive);
$arrayTime = $arrayTime + testArray($oneToFive);
$ifTime = $ifTime + testIf($oneToFive);
} else {
$ifTime = $ifTime + testArray($oneToFive);
$arrayTime = $arrayTime + testArray($oneToFive);
$switchTime = $switchTime + testIf($oneToFive);
}
}
echo 'total if / else time: '.$ifTime.BR;
echo 'total case time: '.$switchTime.BR;
echo 'total array time: '.$arrayTime.BR;
echo BR;
if ($ifTime > $switchTime) {
echo 'switch is quicker by '.($ifTime - $switchTime).BR;
} else {
echo 'if / else is quicker by '.($switchTime - $ifTime).BR;
}
function testSwitch($oneToFive) {
$time_start = microtime(true);
switch($oneToFive) {
case 1: $z = 1; break;
case 2: $z = 2; break;
case 3: $z = 3; break;
case 4: $z = 4; break;
case 5: $z = 5; break;
}
$time_end = microtime(true);
$time = $time_end - $time_start;
return $time;
}
function testIf($oneToFive) {
$time_start = microtime(true);
if (1 == $oneToFive) {
$z = 1;
} elseif(2 == $oneToFive) {
$z = 2;
} elseif(3 == $oneToFive) {
$z = 3;
} elseif(4 == $oneToFive) {
$z = 4;
} elseif(5 == $oneToFive) {
$z = 5;
}
$time_end = microtime(true);
$time = $time_end - $time_start;
return $time;
}
function testArray($oneToFive){
$time_start = microtime(true);
$array = array(0,1,2,3,4,5);
$result = $array[$oneToFive];
$time_end = microtime(true);
$time = $time_end - $time_start;
return $time;
}
preferences:
40.43 ms | 407 KiB | 5 Q