xamenrax
xamenrax

Reputation: 1744

Speed up Rails .each method on relation

In my project i have query looking like this:

@authorizer.user_profile.garden_locations.each {...}

Can I make it faster with smth like this? :

@authorizer.user_profile.garden_locations.find_each {...}

or even with:

GardenLocation.where(user_profile_id: @authorize.user_profile.id).find_each {...}

Note that user_profile_id field of garden_locations table is already indexed

Upvotes: 0

Views: 129

Answers (1)

dodecaphonic
dodecaphonic

Reputation: 459

Of the options you provided, the one that is likely to provide the most gain is the last one (though marginally more than the second one) — considering you have a large enough dataset.

That would be the case because find_each will fetch things in batches, loading smaller datasets in memory at each time. That should keep the memory profile stable as the size of the data grows.

All that said, benchmark the differences. It's pretty easy to do, and you'll learn a lot about what ActiveRecord does.

Upvotes: 1

Related Questions