I know that Larevel cursor method uses LazyCollection and PHP generator feature, but I am quite confused by the memory usage, here are some code I have.
function generator($max)
{
for ($i = 0; $i < $max; $i++) {
yield $i;
}
}
Route::get('/', function () {
dump(memory_usage());
$g = generator(5000000);
$count = 0;
foreach ($g as $a) {
$count += $a;
}
dump($count);
dump(memory_usage());
dump('done');
});
As you can see that it does not use much memory, becasuse it's generating the value one by one and add together rather than creating the whole array in the memory.
And Laravel also has a similar feature which is cursor method. (I have 25000 User records in DB)
Route::get('/', function () {
dump(memory_usage());
$users = User::cursor();
$count = 0;
foreach ($users as $a) {
$count += 1;
}
dump($count);
dump(memory_usage());
dump('done');
});
Here is the optput
I'm now very confused, it's using some memroy, not like the previous example which uses very litter memory, and I think it's still pulling the record one by one.
if I use this $users = User::all(); it uses much more memory about double size of this $users = User::cursor(); one.
Hopefully, I made my point (why the ORM one uses some memory, whereas the generator method does not use any), I think this not specific to PHP and Laravel, but I need a concrete example for generators and ORM. If some could explain this is much appreciated. I am still waiting for the answer cheers.