28
Normal Functions vs Anonymous Functions: Speed and Extensibility
No comments · Posted by joshtime in PHP
PHP5.3 comes out with a new anonymous function feature.
This new feature adds a lot of new flexibility to PHP scripts. What caught my eye more is that a function can be stored inside a variable. Normal functions can not be unset. This is usually fine. But, when inplementing a plugin system to a php script (such as WordPress plugins), anonymous functions can really help. First, there is the original function for doing task X inside a script. But, the script loads a plugin (another php file; like WordPress Plugins) and that new file overrides the function for doing task X. This new feature opens a vast array of new ways to create plugins in PHP.
Here is an example of what I just described above:
Speed
So, are normal functions faster, anonymous functions faster, or are they the same?
I created a simple script that tests it. There are two empty functions. functionn is the normal function. functionc is the anonymous function.
<?php
// Empty function
function n() {
}
// Empty anonymous function inside a variable
$c = function() {
};
$i = 0;
while ($i < 10000) {
n();
$c();
++$i;
}
Xdebug was used to profile the speed and I used WinCacheGrind to view the data.
The results were very interesting.
My results show me that running 10,000 times of function n took a total cumulative time of 69 ms while running 10,000 times of the anonymous function took only 53 ms. The anonymous function was 30.1 percent faster than running the normal function.
*note* I ran other tests that run 50,000 times or 100,000 times show that the anonymous function is only 10 percent faster than a normal function but is still faster
anonymous functions · function · PHP · plugin · speed
