Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is using native PHP functionality faster than doing the same thing in PHP loops? Why?

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 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.

  • 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 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?

like image 711
timetofly Avatar asked Sep 04 '14 18:09

timetofly


People also ask

Which is the fastest loop in PHP?

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 ).

Which is faster foreach or for loop PHP?

The 'foreach' is slow in comparison to the 'for' loop. The foreach copies the array over which the iteration needs to be performed.


1 Answers

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.

like image 110
Carlos Avatar answered Oct 03 '22 06:10

Carlos