ActiveRecord的:大小VS计数 [英] ActiveRecord: size vs count
问题描述
在Rails中,你可以找到的记录同时使用 Model.size
和 Model.count
的数量。如果你要处理更复杂的查询是没有任何优势,使用一种方法比其他?他们是如何不同?
In Rails, you can find the number of records using both Model.size
and Model.count
. If you're dealing with more complex queries is there any advantage to using one method over the other? How are they different?
例如,我有用户的照片。如果我想向用户展示了一个表,他们有多少照片都将运行 user.photos.size
的许多情况下比更快或更慢user.photos.count
?
For instance, I have users with photos. If I want to show a table of users and how many photos they have, will running many instances of user.photos.size
be faster or slower than user.photos.count
?
谢谢!
推荐答案
您应该阅读<一个href="http://web.archive.org/web/20100210204319/http://blog.hasmanythrough.com/2008/2/27/count-length-size">that,它仍然是有效的。
You should read that, it's still valid.
您会适应你请根据您的需要的功能。
You'll adapt the function you use depending on your needs.
基本上是:
-
如果你已经装载的所有条目,比如
User.all
,那么你应该使用长度
来避免另一个数据库查询
if you already load all entries, say
User.all
, then you should uselength
to avoid another db query
如果您有没有什么装,使用计数
来进行计数查询您的分贝
if you haven't anything loaded, use count
to make a count query on your db
如果你不想理会这些考虑,使用尺寸
将调整
if you don't want to bother with these considerations, use size
which will adapt
这篇关于ActiveRecord的:大小VS计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!