我想计算一些数组中的值的数量.
count和之间有什么区别sizeof?
$recips = array();
echo count($recips);
echo sizeof($recips);
Run Code Online (Sandbox Code Playgroud)
Tho*_*ser 10
'sizeof'是'count'的别名 - 至少根据PHP手册!
实际上,这两个函数的行为有所不同,至少在执行时间方面是这样 - sizeof执行时间要长得多!
结论是:sizeof不是count的别名
例:
<?php
$a = array();
for ($i = 0; $i < 1000000; ++$i) {
$a[] = 100;
}
function measureCall(\Closure $cb)
{
$time = microtime(true);
call_user_func($cb);
return microtime(true) - $time;
}
for ($i = 0; $i < 3; ++$i) {
echo measureCall(function () use ($a) {
for ($i = 0; $i < 10000000; ++$i) {
count($a);
}
}) . " seconds for count!\n";
echo measureCall(function () use ($a) {
for ($i = 0; $i < 10000000; ++$i) {
sizeof($a);
}
}) . " seconds for sizeof!\n";
}
Run Code Online (Sandbox Code Playgroud)
结果是:
0.9708309173584 seconds for count!
3.1121120452881 seconds for sizeof!
1.0040831565857 seconds for count!
3.2126860618591 seconds for sizeof!
1.0032908916473 seconds for count!
3.2952871322632 seconds for sizeof!
Run Code Online (Sandbox Code Playgroud)
更新:此测试在PHP 7.2.6上执行