vit*_*tto -1 php optimization benchmarking
也许这是一个愚蠢的问题,但更快的是什么?
<?php
function getCss1 ($id = 0) {
if ($id == 1) {
return 'red';
} else if ($id == 2) {
return 'yellow';
} else if ($id == 3) {
return 'green';
} else if ($id == 4) {
return 'blue';
} else if ($id == 5) {
return 'orange';
} else {
return 'grey';
}
}
function getCss2 ($id = 0) {
$css[] = 'grey';
$css[] = 'red';
$css[] = 'yellow';
$css[] = 'green';
$css[] = 'blue';
$css[] = 'orange';
return $css[$id];
}
echo getCss1(3);
echo getCss2(3);
?>
Run Code Online (Sandbox Code Playgroud)
我怀疑if语句更快但我更喜欢问!
getCss1(if语句)大约是getCss2我的基准测试的两倍(数组访问).
结果来自microtime():
getCss1 called 10,000 times in 0.016569852828979 seconds
getCss2 called 10,000 times in 0.037255048751831 seconds
Run Code Online (Sandbox Code Playgroud)
根据评论,我同意使用翻译数组的可维护性.$css在删除功能开销和数组重新声明的情况下,直接访问速度明显加快.
getCss1 called 10,000 times in 0.016607999801636 seconds
$css accessed 10,000 times in 0.0026898384094238 seconds
Run Code Online (Sandbox Code Playgroud)
注意:在Mac OS X 10.8上运行PHP 5.3.15.我还改变了调用顺序$id以测试执行路径.
| 归档时间: |
|
| 查看次数: |
136 次 |
| 最近记录: |