<?php
message('start');
$a = range(0, 200000);
message('create array');
$chunkGenerator = function ($array, $size, $preserveKeys = false) {
$i = 0;
while (true) {
$offset = $size * $i++;
$sliced = array_slice($array, $offset, $size, $preserveKeys);
if (count($sliced) === 0) {
break;
}
yield $sliced;
}
};
message('defined generator');
foreach ($chunkGenerator($a, 1000) as $chunk) {
// nothing to do
}
message('use generator');
foreach (array_chunk($a, 1000) as $chunk) {
// nothing to do
}
message('use array_chunk');
message('end');
function message($msg)
{
echo sprintf(
"%-3d MB %-3d MB %s" . PHP_EOL,
memory_get_usage() / 1024 / 1024,
memory_get_peak_usage() / 1024 / 1024,
$msg
);
}