I was curious how fast PHP's new anonymous functions were, so I spent a little time benchmarking. Here's what I discovered.
Benchmarked in PHP 5.3.0.
The expense of declaring an anon function is only 2µs or 2/1000 ms. 500 iterations will cost you about 1ms. Now, most of my scripts never iterate through that much data. So, 40 iterations will only cost you about 8/100ms or .08ms. A negligible hit.
My take is, anonymous functions are useful for syntax optimization in scripts that do not have many iterations. I will probably use them in my scripts as long as I never spend more than 1 or 2ms (500-1000 declarations) extra on it.
At the end of the day. We just have to remember that anon functions may be a boost to our syntax beauty, but are a HIT to our execution time. The overhead on executing a predeclared function is only 300 picoseconds or 3/10000 -- about 7 times faster than the overhead on an anonymous function.
It's important to remember that there's a major difference between create_function() and function(){} in memory usage. Since the anonymous functions are throw away functions the memory usage is impacted by only one declaration. The function is destroyed in memory as soon as it isn’t needed anymore (not sure when/where that is, but my guess is after exiting the function it is passed to). Which makes it UNLIKE create_function() which stores every function in memory (at about 464 bytes a piece for an empty function).
Comments