Question

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.)

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top