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:
- Say I have a large array with 1000 elements. Each value is just an integer userid. I want to see if a particular userid is in the array, and I happen to know it will be towards the end of the array (as it would have been added recently). I have two options: a) do a regular PHP
foreach
loop that goes through the whole array until it finds the userid, or b) do anarray_reverse()
on the array and do the sameforeach
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.
- If I have a large multidimensional array where each value is [messageid, message], will it be slower to use a
foreach
loop to find a particular message by id, than it is to set the messageid as the key for the element and doingisset(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?