开发者

Performance on finder methods to retrieve database data

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 fin开发者_如何学Pythonder methods?


Don't fetch all of 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 find or where methods 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_values or select_rows when 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:

@users = Users.all

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜