这是一个类似的问题,以最快的方式来确定一个整数是否在两个整数(包括)与已知的值集之间,但由于php不是严格键入的,因此接受的答案在php中不起作用(据我所知)没有可控整数溢出.
这里的用例是确定整数是否介于65和90之间("A"和"Z"的ASCII值).这些界限可能有助于优化解决方案,因为64是2的幂并且充当该问题的边界条件.
到目前为止我唯一提出的伪优化是:
//$intVal will be between 0 and 255 (inclusive)
function isCapital($intVal)
{
//255-64=191 (bit mask of 1011 1111)
return (($intVal & 191) <= 26) && (($intVal & 191) > 0);
}
Run Code Online (Sandbox Code Playgroud)
与普通的双重比较相比,这个功能并没有太大的改进(可能更慢)$intVal >= 65 && $intVal <= 90
,但它正是我在尝试优化时开始前进的地方.
function isCapitalBitwise($intVal) {
return (($intVal & 191) <= 26) && (($intVal & 191) > 0);
}
function isCapitalNormal($intVal) {
return $intVal >= 65 && $intVal <= 90;
}
function doTest($repetitions) {
$i = 0;
$startFirst = microtime();
while ($i++ < $repetitions) {
isCapitalBitwise(76);
}
$first = microtime() - $startFirst;
$i = 0;
$startSecond = microtime();
while ($i++ < $repetitions) {
isCapitalNormal(76);
}
$second = microtime() - $startSecond;
$i = 0;
$startThird = microtime();
while ($i++ < $repetitions) {
ctype_upper('A');
}
$third = $startThird - microtime();
echo $first . ' ' . $second . ' ' . $third . PHP_EOL;
}
doTest(1000000);
Run Code Online (Sandbox Code Playgroud)
在我的系统上,它返回:
0.217393 0.188426 0.856837
Run Code Online (Sandbox Code Playgroud)
PHP在按位操作方面不如编译语言好......但更重要的是,我不得不进行一百万次比较,以获得不到百分之三百分之一秒的差异.
ctype_upper()
通过这些其他比较方式,即使是"你可以每年节省几秒CPU时间"的范围,还有额外的好处,你不必先打电话ord()
.
为了便于阅读.追求可维护性.编写您的应用程序,然后对其进行分析以查看您的真正瓶颈所在.