<?php
function mapCallback1($callback, $array){
$output = [];
array_map(function($value) use ($callback, &$output) {
$callback($value, function($value) use (&$output) {
$output[] = $value;
});
}, $array);
return $output;
}
function mapCallback2($callback, $array){
$output = [];
$push = function ($value) use (&$output) {
$output[] = $value;
};
foreach ($array as $value) {
$callback($value, $push);
}
return $output;
}
$square = function ($x, $push) {
$push($x * $x);
};
$t = microtime(1);
for ($i = 100000; $i--;) mapCallback1($square, [1, 2, 3]);
echo 1000 * (microtime(1) - $t) . PHP_EOL;
$t = microtime(1);
for ($i = 100000; $i--;) mapCallback2($square, [1, 2, 3]);
echo 1000 * (microtime(1) - $t) . PHP_EOL;
var_dump(mapCallback1($square, [1, 2, 3]));
var_dump(mapCallback2($square, [1, 2, 3]));
preferences:
31.78 ms | 402 KiB | 5 Q