I am using Ruby on Rails 3.0.7 and I would like to know what are advantages and disavantages (relating to performance) to use the User.all method and then perform finder methods on the result for each request needed instead of use User.find(<id>) to retrieve each record singly.
I ask this because in my view file I have something like this:
accounts.each { |account|
puts account.user.name
}
UPDATE
For example, how the Stackoverflow website would handle tags regarding finder methods?
Don’t fetch
allof anything unless you’re sure the data set is very small, on the order of dozens of records at most. Fetching all users is a recipe for disaster as the memory usage of this operation will increase linearly with the number of users on your system.You must use the
findorwheremethods when retrieving sub-sets under most circumstances unless you can be absolutely sure that the number of records involved is trivial.I would even advocate using
select_valuesorselect_rowswhen all you need is a tiny bit of data without the overhead of a model, something that works well for large tabular lists.Remember when you load a model, you load everything associated with it by default. For users this could include their extended biography, their address, their favorite color, their email, their password, and all you use is their name before throwing that object away. Fetch only what you need if performance is a concern.
It is almost always a mistake to have the following in your controller:
What you need to do is paginate or that page will get progressively slower as more users sign up on your system. At some point the page will never render properly as it will time out first.