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 :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%)* :
And the third one (100%) :