Answers:
根据phpbench:
预先计算循环的长度值得吗?
//pre-calculate the size of array
$size = count($x); //or $size = sizeOf($x);
for ($i=0; $i<$size; $i++) {
//...
}
//don't pre-calculate
for ($i=0; $i<count($x); $i++) { //or $i<sizeOf($x);
//...
}
给出了一个具有1000个键和1个字节值的循环。
+---------+----------+
| count() | sizeof() |
+-----------------+---------+----------+
| With precalc | 152 | 212 |
| Without precalc | 70401 | 50644 |
+-----------------+---------+----------+ (time in µs)
所以我个人更喜欢在pre calc中使用count()而不是sizeof() 。
根据它们,它们是相同的 sizeof()
在没有任何理由担心“更快”的情况下,始终为人类优化。这对人类读者来说更有意义?
根据该网站,sizeof()
是的别名count()
,因此它们应运行相同的代码。也许sizeof()
有一点点开销,因为它需要解决count()
?虽然应该很小。
<?php
//Creating array with 1 000 000 elements
$a = array();
for ($i = 0; $i < 1000000; ++$i)
{
$a[] = 100;
}
//Measure
$time = time();
for ($i = 0; $i < 1000000000; ++$i)
{
$b = count($a);
}
print("1 000 000 000 iteration of count() took ".(time()-$time)." sec\n");
$time = time();
for ($i = 0; $i < 1000000000; ++$i)
{
$b = sizeof($a);
}
print("1 000 000 000 iteration of sizeof() took ".(time()-$time)." sec\n");
?>
结果是:
1 000 000 000 iteration of count() took 414 sec
1 000 000 000 iteration of sizeof() took 1369 sec
所以就用吧count()
。
1 000 000 000 iteration of count() took 525 sec
1 000 000 000 iteration of sizeof() took 1361 sec