Skip to content

Instantly share code, notes, and snippets.

@lyrixx
Created Apr 22, 2020
Embed
What would you like to do?
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