老问题Length-size-count的区别


  • Starting from Ruby 1.8.7, Array#count is the same of Array#size.
  • Please note that Array#count doesn't exist in Ruby versions lower than 1.8.7 so if you are running Ruby 1.8.6 in production, it will raise a NoMethodError.
  • Also, make sure you are talking about arrays. In ActiveRecord, for example, #size and #count are slightly different. #size understands caching like counter cache, while count doesn't.
  • size和length是完全一样的,都返回Array或者Hash中元素的个数,而count可以接受一个block作为参数。
  • 但是在ActiveRecord中,区别就来了。size考虑缓存,而count不会,他每次都会执行一个sql count语句。

比如你的Rails代码中
@subjects = Subject.includes(:users).all

在你的view中,你要获取每个subject下user的数目

<%= subject.users.count %>
<%= subject.users.size %>


这里区别就大了,如果你用的是count,那么你就制造了N+1查询问题了,查看你的log你就会看到很多条sql count记录。

而如果你用size,或者length,你就不会有这个问题。

原因就是因为count不考虑任何缓存,每次都执行一个count .如果不清楚这个区别,那么就会疑惑明明已经做了eager loading了,为什么不起作用呢?而其实是用错了方法。



阅读量: 307
发布于:
修改于: