【发布时间】:2019-11-14 04:03:48
【问题描述】:
我一直认为in_array严格模式会更快或者至少和非严格模式一样的速度。但是经过一些基准测试后,我注意到在搜索整数时它们之间的执行时间存在巨大差异。字符串和数组测试表明严格模式更快。为什么?
测试代码 - (PHP 7.2.1):
<?php
$array = array_fill(0, 10000, 12345);
for ($i=0; $i<100000; $i++) {
in_array($i, $array, true);
}
时间 php test.php
php -c test.php 12.98s user 0.04s system 98% cpu 13.234 total
<?php
$array = array_fill(0, 10000, 12345);
for ($i=0; $i<100000; $i++) {
in_array($i, $array, false);
}
时间 php test.php
php -c test.php 6.44s user 0.04s system 99% cpu 6.522 total
【问题讨论】:
-
根据文档:
If the third parameter strict is set to TRUE then the in_array() function will also **check the types** of the needle in the haystack.- 所以会有额外的操作(类型比较) -
@B001ᛦ 不确定 C 中的实际实现,但可以想象严格检查只是启用
===而不是==和===在 PHP 代码中客观上更快。 -
在您的示例中,它们都匹配类型。如果没有一个类型匹配怎么办?尝试搜索字符串而不是整数?也许 in_array 首先检查类型,然后如果匹配,则检查是否相等。因此,如果类型匹配,则需要稍长一些,如果不匹配,则速度会稍快。
标签: php php-internals