Skip to content

Instantly share code, notes, and snippets.

@gavinkalika
Created March 29, 2023 02:26
Show Gist options
  • Select an option

  • Save gavinkalika/cdd8d881b3fd34a5ff457eb57f7a771b to your computer and use it in GitHub Desktop.

Select an option

Save gavinkalika/cdd8d881b3fd34a5ff457eb57f7a771b to your computer and use it in GitHub Desktop.
Comparing the PHP 8.2 memory performance between array and generators
<?php
$size = 100000;
$startTime = microtime(true);
$memoryStart = memory_get_usage();
$array = range(1, $size);
$sum = 0;
foreach ($array as $value) {
$sum += $value;
}
$memoryEnd = memory_get_usage();
$endTime = microtime(true);
echo "Foreach Loop: Execution Time: " . ($endTime - $startTime) . " seconds\n";
echo "Foreach Loop: Memory Usage: " . ($memoryEnd - $memoryStart) . " bytes\n\n";
$startTime = microtime(true);
$memoryStart = memory_get_usage();
function createGenerator($size, $array) {
foreach($array as $v) {
yield $v;
}
}
$generator = createGenerator($size, range(1, $size));
$sum = 0;
foreach ($generator as $value) {
$sum += $value;
}
$memoryEnd = memory_get_usage();
$endTime = microtime(true);
echo "Generator: Execution Time: " . ($endTime - $startTime) . " seconds\n";
echo "Generator: Memory Usage: " . ($memoryEnd - $memoryStart) . " bytes\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment