为什么foreach这么慢? [英] Why is foreach so slow?
问题描述
为什么是一个本地语言结构显然比执行自己的逻辑慢?
也许这与事实,foreach工作的副本数组?
或者,也许这是因为在循环foreach时,每次迭代都会改变内部数组指针,指向下一个元素?
引用 foreach
的手册页:
:除非数组被引用,否则
foreach对
指定数组的副本进行操作,而对阵列
本身不作操作。 foreach在数组指针上有一些副作用
。
据我所知,你链接的第三个测试不会做这两件事中的任何一件 - 这意味着两个测试不会做同样的事情 - 这意味着你没有比较两种编写相同代码的方式。 (我也会说这种微观优化在实际应用中根本就不重要 - 但是我想你已经知道了,只是出于好奇而问了)
在这个测试中还有一件事情是不正确的:它只做一次测试;对于一个更好的测试来说,对所有这些不止一次的测试可能是有用的 - 在100微秒的时间内进行测试并不需要做太大的改变。
(考虑到第一次测试的刷新率在300%到500%之间不等...)
<
对于那些不想点击的人来说,这是第一个测试(我得到了3xx%,443%和529%):
foreach($ aHash as $ key => $ val){
$ aHash [$ key]。=a;
第三个(100%):
$ key = array_keys($ aHash);
$ size = sizeOf($ key); ($ i = 0; $ i <$ size; $ i ++){
$ aHash [$ key [$ i]]。=a;
。
}
PHPBench.com runs quick benchmark scripts on each pageload. On the foreach test, when I load it, foreach takes anywhere from 4 to 10 times as long to run than the third example.
Why is it that a native language construct is apparently slower than performing the logic oneself?
Maybe it has to do with the fact that foreach works on a copy of the array ?
Or maybe it has to do with the fact that, when looping with foreach, on each iteration, the internal array pointer is changed, to point to the next element ?
Quoting the relevant portion of foreach
's manual page :
Note: Unless the array is referenced, foreach operates on a copy of the specified array and not the array itself. foreach has some side effects on the array pointer.
As far as I can tell, the third test you linked to doesn't do any of those two things -- which means both tests don't do the same thing -- which means you are not comparing two way of writing the same code.
(I would also say that this kind of micro-optimization will not matter at all in a real application -- but I guess you already know that, and just asked out of curiosity)
There is also one thing that doesn't feel right in this test : it only does the test one time ;; for a "better" test, it might be useful to test all of those more than once -- with timings in the order of 100 micro-seconds, not much is required to make a huge difference.
(Considering the first test varies between 300% and 500% on a few refreshes...)
For those who don't want to click, here's the first test (I've gotten 3xx%, 443%, and 529%) :
foreach($aHash as $key=>$val) {
$aHash[$key] .= "a";
}
And the third one (100%) :
$key = array_keys($aHash);
$size = sizeOf($key);
for ($i=0; $i<$size; $i++) {
$aHash[$key[$i]] .= "a";
}
这篇关于为什么foreach这么慢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!