小小的測試,小小的趣味。
原始碼:下載
//copyright Lawrence Truett and FluffyCat.com 2009, all rights reserved
define('BR', '<'.'BR'.'>');
echo 'Performance Testing PHP if / else VS switch with 100,000 iterations'.BR.BR;
$ifTime = 0;
$switchTime = 0;
for ($x = 0; $x < 100000; $x++) {
$oneToFive = rand(1,5);
if (0 == fmod($x,2)) {
$switchTime = $switchTime + testSwitch($oneToFive);
$ifTime = $ifTime + testIf($oneToFive);
} else {
$ifTime = $ifTime + testIf($oneToFive);
$switchTime = $switchTime + testSwitch($oneToFive);
}
}
echo 'total if / else time: '.$ifTime.BR;
echo 'total case time: '.$switchTime.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;
}
參考資料:http://www.fluffycat.com/PHP-Design-Patterns/PHP-Performance-Tuning-if-VS-switch/
沒有留言:
張貼留言