Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does PHP engine optimize anonymous functions within loops?

I have an array which stores multiple references to a single anonymous function:

$fns = array();
//some code
$fn = function(){
    echo 'this is closure 12345... < 67890';
    // etc etc..
};
for($x=12345; $x<67890; ++$x){
    $fns[$x] = $fn;
}

As can be seen, we're creating only one anonymous function.

What if we put the function declaration inside of the loop? :

$fns = array();
//some code
for($x=12345; $x<67890; ++$x){
    $fns[$x] = function(){
        echo 'this is closure 12345... < 67890';
        // etc etc..
    };
}

Is the engine smart enough to recognize that only one object needs to be created?

Does the above code create only one object or does it create one object per iteration?

(Question is targeted at both HHVM and Zend Engine.)

like image 756
Pacerier Avatar asked Aug 05 '13 05:08

Pacerier


People also ask

Does PHP have anonymous functions?

Anonymous functions, also known as closures , allow the creation of functions which have no specified name. They are most useful as the value of callable parameters, but they have many other uses. Anonymous functions are implemented using the Closure class. printf("Hello %s\r\n", $name);

Which is are true about anonymous functions?

An anonymous function is a function that is not stored in a program file, but is associated with a variable whose data type is function_handle . Anonymous functions can accept multiple inputs and return one output. They can contain only a single executable statement.

Are anonymous functions faster?

Anonymous objects are faster than named objects. But calling more functions is more expensive, and to a degree which eclipses any savings you might get from using anonymous functions. Each function called adds to the call stack, which introduces a small but non-trivial amount of overhead.

What is an anonymous function how is it different from normal function in PHP?

Anonymous function is a function without any user defined name. Such a function is also called closure or lambda function. Sometimes, you may want a function for one time use. Closure is an anonymous function which closes over the environment in which it is defined.


1 Answers

If you create the function inside the loop, you're creating 300 individual anonymous function objects. PHP does not optimize this away, since maybe that's what you want. That's a lot less efficient than creating the function once before the loop.

Here's the proof that two independent objects get created: http://3v4l.org/f3cdE

like image 115
deceze Avatar answered Sep 22 '22 15:09

deceze