Rails 中的预先加载和延迟加载 [英] eager loading and lazy loading in rails

查看:50
本文介绍了Rails 中的预先加载和延迟加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对预先加载和延迟加载感到困惑,rails 查询的性能有什么区别吗?

I am confused about eager loading and lazy loading, is there any difference in the performance of rails queries?

有没有办法同时实现这两种方式?

Is there any way to implement both ways?

推荐答案

急切加载

提高性能的一种方法是减少 SQL 查询的数量.您可以通过预先加载来实现这一点.

One way to improve performance is to cut down on the number of SQL queries. You can do this through eager loading.

User.find(:all, :include => :friends)

这里你只触发了两个查询:

Here you are firing only two queries :

1) 一个供所有用户使用.

1) One for all users.

2) 用户的所有朋友一份.

2) One for all friends of users .

延迟加载 :

当您有一个对象与许多对象相关联时,例如用户有很多朋友,并且您想在 Orkut 中显示一个列表,您可以发起与朋友一样多的查询,再加上一个对象本身.

When you have an object associated with many objects like a User has many Friends and you want to display a list as in Orkut you fire as many queries as there are friends, plus one for the object itself.

users = User.find(:all)

然后查询每个用户好友,例如:

Then query for each user friend , like :

users.each do |user|
  friend = Friend.find_by_user_id(user.id)
end

这里

1) 针对所有用户的一个查询.

1) One query for all users.

2) N 查询 N 号.的用户朋友.

2) N query for N no. of users friends .

查看:Rails 3:延迟加载与预先加载

希望能帮助你理解这一点.

Hope that will help you to understand this .

这篇关于Rails 中的预先加载和延迟加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆