Is using PHP built-in functions faster than executing the same function in PHP loops? What for?

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?

+5
source share
2 answers

You can see the PHP tests of the time spent on functions here, in my opinion, they are not very different. What for? More code or less code, less code or more basic comparison functions take less floating point operations than the actual function, then again these functions work in basic comparison methods, such as array_reverse (), which do not require much time and require processing.

http://www.phpbench.com/

EDIT: I agree with FuzzyTree that you should focus on the efficiency of the algorithm, not the functions themselves.

0
source

The array_xxx () functions are composed of loops, and they are most optimized as they can be. I do not think that you can do something better on your own with the help of "manual" foreach / for / while. Therefore, I prefer to use predefined functions.
(By the way, in the most primitive form of a programming language, there is only one kind of cycle, but we can modulate it into three forms :))

-1
source

Source: https://habr.com/ru/post/1201844/


All Articles