Skip to content

Instantly share code, notes, and snippets.

@lyrixx
Created April 22, 2020 13:20
Show Gist options
  • Save lyrixx/5b7ed2cf31ac60f25f071ec1a92d4139 to your computer and use it in GitHub Desktop.
Save lyrixx/5b7ed2cf31ac60f25f071ec1a92d4139 to your computer and use it in GitHub Desktop.
Very low memory usage iterator
<?php
function m()
{
$memory = round(memory_get_usage() / 1024 / 1024, 2);
$frame = debug_backtrace(0, 1)[0];
$file = basename($frame['file']);
$line = $frame['line'];
printf("%s:%d | %sMb\n", $file, $line, $memory);
}
function gen(): \iterator
{
$data = str_repeat('x', 10 * 1024 * 1024);
$i = 0;
while ($data) {
m();
yield $data;
m();
unset($data);
yield;
m();
++$i;
// Simulate the API return nothing
if ($i == 3) {
$data = false;
} else {
$data = str_repeat('x', 10 * 1024 * 1024);
}
m();
}
};
m();
foreach ($gen = gen() as $k => $v) {
$gen->next();
m();
unset($k, $v);
m();
}
m();
JHS6W:36 | 0.37Mb
JHS6W:19 | 10.38Mb
JHS6W:21 | 10.38Mb
JHS6W:40 | 10.38Mb
JHS6W:42 | 0.37Mb
JHS6W:24 | 0.37Mb
JHS6W:32 | 10.38Mb
JHS6W:19 | 10.38Mb
JHS6W:21 | 10.38Mb
JHS6W:40 | 10.38Mb
JHS6W:42 | 0.37Mb
JHS6W:24 | 0.37Mb
JHS6W:32 | 10.38Mb
JHS6W:19 | 10.38Mb
JHS6W:21 | 10.38Mb
JHS6W:40 | 10.38Mb
JHS6W:42 | 0.37Mb
JHS6W:24 | 0.37Mb
JHS6W:32 | 0.37Mb
JHS6W:45 | 0.37Mb
@lyrixx
Copy link
Author

lyrixx commented Apr 22, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment