jpfuentes2 / php-activerecord

ActiveRecord implementation for PHP
http://www.phpactiverecord.org/
Other
1.32k stars 443 forks source link

Feature: Faster Eager Loading #550

Closed brianmuse closed 8 years ago

brianmuse commented 8 years ago

This PR improves the logic of eager loading, especially when eager loading a lot of related models.

The existing code would loop through each model that was being eager loaded onto and then (nested) loop through all the possible related models to add those relationships.

The new approach first maps all the related models by their keys so that in the second loop they are easily accessible without traversing the entire array.

My big O notation is rusty, but I think this is roughly-- Previously: O(n*m) Now: O(m) + O(n*log(m))

..but actually a little bit better cause we also improved the $used_model array to be a map as well.

I first noticed that this took a while when dealing with an eager load that loaded ~200 models onto 10 results. Anecdotally on my local machine, this took that from a 400ms task to about 150ms (it still took 150ms to instantiate the 200 models, but that's a separate issue).

Rican7 commented 8 years ago

Just going to reference robinpowered/php-activerecord#11 here.

Rican7 commented 8 years ago

This LGTM 👍

jpfuentes2 commented 8 years ago

Love it; nice work!