Jump to content

Should an anonomous function be used for this?


NotionCommotion

Recommended Posts

I have the following script.  doThis() is only used for this single use.  Should I use an anonymous function instead?  Reasons why or why not (i.e. speed, doesn't use up a function name, etc)?  How should is it be implemented?  Thanks

$a=array(10,20,30);

for ($x=0; $x<=10; $x++) {
    $z.=doThis($x,$a[1],50);
}

function doThis($a,$b,$c) {return $a+$b+$c;}


Not much point in using any array functions on array $a as the only item referenced is $a[1]

 

However I constructed an array with values [0..10] and used array_walk() with an anonymous function and benchmarked it against your code. Your current code was marginally faster so I'd stick with that.

<?php
function doThis(&$a,$b,$c) {return $a+$b+$c;}

$a=array(10,20,30);

$inc = $a[1] + 50;

$t1 = microtime(1);
for ($i=0; $i<10000; $i++) {
    $y = range(0,10);
    array_walk($y,function(&$v,$k,$b){$v += $b;},$inc);

}

$t2 = microtime(1);

for ($i=0; $i<10000; $i++) {
    $z = [];
    for ($x=0; $x<=10; $x++) {
        $z[]=doThis($x,$a[1],50);
    }
}

$t3 = microtime(1);

printf ("<pre>%-10s %0.4f\n%-10s %0.4f\n</pre>", 
            'anonymous',$t2-$t1, 
            'doThis()', $t3-$t2);
?>

RESULT
anonymous  0.1160
doThis()   0.1030

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.