Foued MOUSSI
Foued MOUSSI

Reputation: 4813

Laravel Chunking Results utility

According to Laravel Documentation

If you need to work with thousands of database records, consider using the chunk method. This method retrieves a small chunk of the results at a time and feeds each chunk into a Closure for processing. This method is very useful for writing Artisan commands that process thousands of records. For example, let's work with the entire users table in chunks of 100 records at a time:

DB::table('users')->orderBy('id')->chunk(100, function ($users) {
    foreach ($users as $user) {
        //
    }
});

Is it supposed to reduce waiting time ?

I can't see how this feature is helpful

Upvotes: 1

Views: 824

Answers (1)

James Clark
James Clark

Reputation: 1325

Chunking allows you to break a big query and subsequent processing task into a repeated step.

The most common application of this technique is to avoid hitting memory limits. If you are loading hundreds of thousands of rows from the database and then doing a transformation process on them, that can chew up a lot of memory and could very easily hit limits defined in php.ini.

Depending on the context, you can push the results to screen as soon as each chunk finishes, which means you have reduced wait time for the initial results while overall processing time has likely increased while result notifications would come in one chunk at a time.

Upvotes: 2

Related Questions