Scott Watermasysk
Optimizing ActiveRecord SQL Memory Usage in Rails
A decent suggestion by Patel Urbanek - Easy to Miss Way to Optimize ActiveRecord SQL Memory Usage in Rails.
Urbanek recommends using select
in your ActiveRecord queries to limit the fields returned and thus save memory. While this certainly will work, I find it messy long term.
- It is not obvious what data you have access to. Your code appears to have access to the user object, but most of the data is missing.
- Similar to #1, other helpers/decorators/etc. that you have in your codebase may have model requirements that are not obvious as well. You pass along this partial object, and you may have some unintended consequences.
- If you use any kind of caching, you may accidentally expose this partial object to completely unaware parts of your app
I typically use two approaches:
pluck
- As suggested in the article, you may be giving up some of your model niceties. Still, it is usually a worthwhile trade-off if the amount of data returned warrants optimization. It can also help expose some code that should not live directly within your model.pluck
andStruct
- when using pluck gets too messy, you can always take the data returned and load it into a struct (or a PORO).