winner1's avatar

chuck vs pagination! memory usage

as laravel doc says: If you need to process a lot (thousands) of Eloquent records, using the chunk command will allow you to do without eating all of your RAM:

so what about pagination?

for example is:

DB::table('users')->paginate(15)

same as

User::chunk(15, function($users){foreach ($users as $user){..}});

in memory usage?

0 likes
3 replies
thoasty's avatar

These methods have a different usecase. I assume you know how paginate works.

But "chunk" retrieves not only 15 entries, but all entries in "packets" of 15 entries. So your ram only loads 15 entries at the same time. But in the end, it will have loaded all entries of the query.

1 like
LNCH's avatar
LNCH
Best Answer
Level 6

When you paginate the results it will add a LIMIT to the SQL query which will only retrieve at most the number of results that fit on one page

So you'll only ever query for 15 results if you've called ->paginate(15)

Chunk will retrieve all the results, but only 15 at a time, to save the memory as you've said

1 like

Please or to participate in this conversation.