NotionCommotion Posted October 2, 2014 Share Posted October 2, 2014 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;} Quote Link to comment Share on other sites More sharing options...
Ch0cu3r Posted October 2, 2014 Share Posted October 2, 2014 Use array_map Quote Link to comment Share on other sites More sharing options...
Frank_b Posted October 2, 2014 Share Posted October 2, 2014 (edited) Ch0cu3r is right. And give functions always reliable names so that you immediately understand what the function does. Edited October 2, 2014 by Frank_b Quote Link to comment Share on other sites More sharing options...
Barand Posted October 2, 2014 Share Posted October 2, 2014 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 Quote Link to comment Share on other sites More sharing options...
NotionCommotion Posted October 3, 2014 Author Share Posted October 3, 2014 Thanks all, I think I am confusing myself, and overly complicating matters. Quote Link to comment Share on other sites More sharing options...
Barand Posted October 3, 2014 Share Posted October 3, 2014 Thanks all, I think I am confusing myself, and overly complicating matters. +1 Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.