This is something I've been wondering for a while. Is performance always better when using native PHP functions than their PHP loop equivalents? Why or why not?
Here are two examples to illustrate the question:
foreach
loop that goes through the whole array until it finds the userid, or b) do an array_reverse()
on the array and do the same foreach
loop until it finds the id (if it exists, it will end this loop sooner). Which is faster?My gut tells me the first option is faster since it does one loop, and the second option is slower because behind the scenes, array_reverse()
is also doing some kind of loop (in C), thereby requiring two loops for the operation.
foreach
loop to find a particular message by id, than it is to set the messageid as the key for the element and doing isset(array[messageid]) && array[messageid]
?Edit: just to clarify, I'm aware the first example can use array_search(), since this is a very simplified example. The main question isn't which one is faster (as benchmarks can let me know easily), but why, as in, what's going on behind the scenes?
The do-while loop is by a considerable amount the fastest loop. do-while is actually faster than while by almost half. I know that they are for different purposes ( while checks the condition before the loop executes and do-while executes at least once ).
The 'foreach' is slow in comparison to the 'for' loop. The foreach copies the array over which the iteration needs to be performed.
You can see PHP benchmarks of time consumed by functions here, in my opinion they are not terribly different. Why? More code or less code, less code or more basic comparison functions take less floating point operations than an actual function, then again those functions operate in basic comparison methods like array_reverse() which are not terribly time-consuming and processing required.
http://www.phpbench.com/
EDIT: I agree with FuzzyTree in the fact that you should focus on the efficiency of the algorithm and not the functions themselves.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With