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
foreachloop that goes through the whole array until it finds the userid, or b) do anarray_reverse()on the array and do the sameforeachloop 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
foreachloop 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?
array_search()orin_array(), which will be faster than scanning the loop withforeach()in either direction. However, I should think that reversing and finding it quickly might be faster than finding it slowly under certain array sizes.array_reverseis a somewhat large operation, but doing it may be faster than aforeachloop with some additional comparison. Of course,for ($i = count($arr) - 1; $i >= 0; $i--)will likely be even faster. In your second case accessing an element by index will be orders of magnitude faster than looping, they're entirely different classes of operation.