Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[7.x] Significant performance issue in Eloquent Collection loadCount() method #34177

Merged
merged 2 commits into from
Sep 7, 2020

Conversation

markokeeffe
Copy link
Contributor

@markokeeffe markokeeffe commented Sep 7, 2020

It appears as though the performance of \Illuminate\Database\Eloquent\Collection::loadCount() has been significantly impacted by this change 5ee0e4d

I was debugging a performance issue in one of our applications and noticed that a call to loadCount() was taking minutes. I profiled with Blackfire.io and saw hundreds of thousands of calls to the getAttribute() method on the Eloquent Model.

I've put together a repository to validate a performance fix: https://github.com/markokeeffe/laravel-load-count-performance

You can follow the steps in README.md to validate the performance impact.

The repo essentially seeds 500 Item models, each with 1000 related ItemLog models. Then two console commands can be run to see the performance difference between the current method and the proposed fix in this PR:

load-count-laraval

blackfire run php artisan load-count-laravel

Wall Time   2min 5s
I/O Wait      29.9s
CPU Time   1min 35s
Memory       18.7MB
Network         n/a     n/a     n/a
SQL           28.5s     4rq

load-count-improved

blackfire run php artisan load-count-improved

Wall Time     23.9s
I/O Wait      22.9s
CPU Time      984ms
Memory       18.7MB
Network         n/a     n/a     n/a
SQL           22.4s     4rq

Check this screenshot from Blackfire.io to see how calling loadCount() on a collection of 500 models results in 501,000 calls to getAttribute()

Screen Shot 2020-09-07 at 17 01 46

Here's a screenshot of the Blackfire.io profile after the fix is applied:

Screen Shot 2020-09-07 at 17 09 52

@GrahamCampbell GrahamCampbell changed the title Significant performance issue in Eloquent Collection loadCount() method [7.x] Significant performance issue in Eloquent Collection loadCount() method Sep 7, 2020
@taylorotwell taylorotwell merged commit 8b84cf5 into laravel:7.x Sep 7, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants