array_map 与循环和操作
使用:
for($i=1; $i<= 10000; ++$i) {
$arrayOfNumbers[] = rand(1, 99999);
}
可以解释一下为什么会有这样的速度差异:
array_map(array($maxHeap, 'insert'), $arrayOfNumbers);
# Avg Time: 0.92856907844543s
# against
foreach($arrayOfNumbers as $number) {
$maxHeap->insert($number);
}
# Avg Time: 1.3148670101166
$maxHeap
是一个对象 class MaxHeap extends SplMaxHeap
Using:
for($i=1; $i<= 10000; ++$i) {
$arrayOfNumbers[] = rand(1, 99999);
}
Can some explain why there is such a speed difference:
array_map(array($maxHeap, 'insert'), $arrayOfNumbers);
# Avg Time: 0.92856907844543s
# against
foreach($arrayOfNumbers as $number) {
$maxHeap->insert($number);
}
# Avg Time: 1.3148670101166
$maxHeap
being an object class MaxHeap extends SplMaxHeap
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
据我所知,与 Sajith Amma 的回答相反,php 不会异步执行任何操作。
我怀疑这实际上是由于
$maxHeap->insert
的查找差异造成的。使用
foreach
循环,您在当前范围内调用$maxHeap->insert
,php 解释器必须查找maxHeap
然后查找在maxHeap
实例上插入
。在您正在运行的脚本范围内,可能存在其他变量,这些变量可能会使查找速度变慢。使用
array_map
,php解释器知道它将调用完全相同的$maxHeap->insert
,它可以只进行一次查找并使用相同的“代码地址”对于其余的迭代。To my knowledge php doesn't do anything asynchronously, in contrast to Sajith Amma's answer.
I suspect that this is actually due to differences in the lookup of
$maxHeap->insert
.With the
foreach
loop the you are calling$maxHeap->insert
within the current scope, the php interpreter has to look upmaxHeap
then lookupinsert
on themaxHeap
instance. Within the scope of the script you are running there might be other variables which can make the lookup slower.With the
array_map
the php interpreter knows it will be calling the exact same$maxHeap->insert
, it can do the lookup just once and use the same 'code address' for the rest of the iterations.这是由于回调函数和普通函数之间的差异造成的。
在第二个中,使用 foreach 迭代数组,每次迭代调用“insert”函数并等待执行(函数返回控制)并继续下一次迭代。
但在 array_map 函数中,“insert”作为回调函数发生,它调用“insert”并且不等待结果并调用数组中下一项的插入。所以速度更快。
希望有帮助。
It is due to the difference between Callback functions and normal functions.
In the second one, iteration of array using foreach, each iteration calls "insert" function and wait for the execution (function return control) and proceed to next iteration.
But in the array_map function, "insert" happens as callback function, it calls "insert" and don't wait for the result and call insert with next item in the array. So it is faster.
Hope it helps.