Created
December 3, 2018 21:43
-
-
Save amcsi/a70c07b5029503f11eeb54e2af865436 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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