13

I'm starting to use functional programming paradigms in php and was wondering what the performance impacts are. Some googling just seems to say that there are some. To be specific, I would like to know:

  • Is there actually a performance impact or is it an urban legend?
  • What is the performance impact (hopefully someone out that has done benchmarks)?
  • What causes this impact (if one exists)?
  • Is it fixed cost, or per execution?

Any resources you guys have would be greatly appreciated :)

Thanks in advance

Alex M
  • 3,506
  • 2
  • 20
  • 23
  • 1
    This answer is the top Google result for "php anonymous function performance" https://hackernoon.com/the-decline-of-stack-overflow-7cb69faa575d – jchook Oct 13 '16 at 02:39

1 Answers1

18

I did some testing with array_map(), calling it with:

  1. The name of a function (array_map('test', $myArray);)
  2. A variable that contains a closure (array_map($test, $myArray);)
  3. A closure (array_map(function{}(), $myArray);)

In all three cases, the function was empty (function test(){})

The results for an array with 1.000.000 items ($myArray = range(1,1000000);)

Function: 0.693s
Variable:0.703s
Closure: 0.694s

For an array of 10.000.000 items, the results are this:

Function: 8.913s
Variable: 8.169s
Closure: 8.117s

So in neither case do we have much overhead, if any.

Also see the 4th comment on http://fabien.potencier.org/article/17/on-php-5-3-lambda-functions-and-closures It comes to the same conclusions. In that comment, you also see that create_function() is significantly slower.

lafor
  • 12,472
  • 4
  • 32
  • 35
Jory Geerts
  • 1,916
  • 15
  • 25
  • Nice answer. Note also that create_function must always parse the php at run time so you'll lose out big time if you use opcode caching. – symcbean Dec 30 '11 at 12:06
  • But what about the entirely nonfunctional equivalent `foreach ($myArray as $foo) { }`? :) – deceze Dec 31 '11 at 01:10
  • 1
    Just did the 10.000.000 test: 4.780s I expected it to be a *bit* faster, but this is a *lot*. (Though a few quick re-runs of the other versions suggest they are also a bit quicker now, but in the sub-second ballpark.) To make things fair, I did `foreach($a AS $i) {test($i);}`, since that 'does the same' as the `array_map() calls`. – Jory Geerts Jan 03 '12 at 14:50
  • @JoryGeerts I would argue the equivelent foreach loop would be something like: `foreach($a as $k => $v) $a[$k] = operation_from_closure($v);` – Chris Seufert Nov 21 '18 at 05:00
  • Here's a quick test for all PHP versions: https://3v4l.org/6AABv – it seems that creating a lambda function and storing it in a variable maybe has about 1% overhead to hardcoded function. Using anonymous lambda function without storing it in a variable has about 15-25% overhead. For details, see https://gist.github.com/mikkorantalainen/3791bb2d58b8b65155d7ad4897174efb – Mikko Rantalainen Dec 10 '20 at 13:55