This is what I have been thinking about for a long time. 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 an integer user identifier. I want to find out if a specific user ID is in the array, and I know that it will be closer to the end of the array (as it would have been added recently). I have two options: a) execute a regular PHP
foreach that goes through the whole array until it finds the user ID, or b) does array_reverse() in the array and does the same foreach until it finds id (if it exists, it will rather finish this loop). Which is faster?
My gut tells me that the first option is faster because it runs one loop, and the second slower, because behind the scenes array_reverse() also runs 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 the
foreach to search for a specific message by id than to set messageid as the key for the element and do isset(array[messageid]) && array[messageid] ?
Edit: just for clarification, I know that the first example can use array_search (), as this is a very simplified example. The main question is not which one is faster (because tests can let me know easily), but why, like what is going on behind the scenes?
source share