I think that usage of build-in functions for arrays in PHP is good idea for some time. These functions could be optimized by PHP itself and so it should be faster in some way. Well, I have found some time to find out which way is faster and here are my results.

I have used my MacBook Air 13″, Intel Core i7 1.7 GHz, 8 GB RAM 1600 MHz DDR3, PHP 5.5.5.

You can see whole source code of this simple benchmark on github.

I have take 4 functions which are used often (in my opinion). Let`s take a look!

Benchmarked functions

Measured times

array_filter
array_filter
array_reduce
array_reduce
array_map
array_map

 

array_walk
array_walk

As you can see direct foreach without any callback call is better in all case. I am disappointed from these results because I expected better times from build-in functions. However it makes sense because for each iteration it must call some function and it takes some time. There is some optimization in build-in functions in comparison to foreach with callback but it is not significant.

Conclusion

Well, it may look that usage of direct foreach is always better then build-in function. I disagree with that because of code readability. You can see in code snippets each type of iteration. Build-in functions are more readable in my opinion. So I still think that usage of build-in functions is a good idea but the reason is different now.

If you have small array (eg. max. tens or hundreds of items) and you do not need realtime response then build-in functions can be used for better readability. If you need as fast as possible code or you have special requirements then write your own foreach (or some else cycle).

Good idea can be to write your own iterator for your special collection. I may make some benchmark for that in the future.

Source code

Napsat komentář

Vaše emailová adresa nebude zveřejněna. Vyžadované informace jsou označeny *