Skip to content

Instantly share code, notes, and snippets.

@amcsi
Created December 3, 2018 21:43
Show Gist options
  • Save amcsi/a70c07b5029503f11eeb54e2af865436 to your computer and use it in GitHub Desktop.
Save amcsi/a70c07b5029503f11eeb54e2af865436 to your computer and use it in GitHub Desktop.
<?php
declare(strict_types=1);
$amountOfLists = 10;
$amountOfItems = 10000;
$initializeArray = function () use ($amountOfLists) {
return array_fill(0, 10, []);
};
// With regular foreach.
$array = $initializeArray();
$start = microtime(true);
foreach (range(0, $amountOfItems) as $_) {
$array[random_int(0, $amountOfLists - 1)][] = true;
}
printf("Regular foreach in %.4f\n", microtime(true) - $start);
// With reduce.
$array = $initializeArray();
$start = microtime(true);
$array = array_reduce(range(0, $amountOfItems), function (array $acc, $_) use ($amountOfLists) {
$acc[random_int(0, $amountOfLists - 1)][] = true;
return $acc;
}, $array);
printf("Regular foreach in %.4f\n", microtime(true) - $start);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment