laravel/laravel — pull request #1314 by vFragosop (2012-10-05 14:07:09+00:00)
Title: Huge performance increase on Eloquents relationships

The current Eloquent's iteration method to match relationships, specially has_many and has_many_and_belongs_to are quite slow. It iterates over one edge of the relationship and then uses array_filter and array_first to identify the models on the other edge that match.

I did some improvements on Relationship::match method. And created a small benchmark to compare performance: paste.laravel.com/7dt

With 250 children matching 50 parents, the results on my Macbook Pro were:

Current Iteration: 187ms (total array iterations = 12550)
Optimized Iteration: 3ms (total array iterations = 300)

The great thing is that this method I'm suggesting grows linearly with the number of models, while the other grows exponentially and if you try to load more models, it's time will increase even more and so it's CPU and memory usage.

On small applications that load 20-30 items per page, this passes unnoticed. But for Laravel to reach enterprise class, this kind of optimization is necessary.