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;}


Link to comment
Share on other sites

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
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.