问题描述
假设有 2 个模型,分别称为 User
和 Post
A 计划"或B 计划"哪个表现更好(快)?
A 计划"
控制器
@users = User.find_all_by_country(params[:country])@posts = Post.find_all_by_category(params[:category])
查看
<%[email protected]_s %>
B 计划"
控制器
@users = User.find_all_by_country(params[:country])@posts = Post.find_all_by_category(params[:category])
查看
<%[email protected]_s %>
在 ruby 中,count
、length
和 size
都差不多关于数组的同样的事情.请参阅此处了解更多信息.
当使用ActiveRecord对象时,count
比length
更好,size
甚至更好.
find_all_by_country
返回一个哑数组,因此您不应使用该方法(因为它总是返回一个数组).相反,使用 where(country: params[:country])
.
我会让 Code School 的 Rails 最佳实践第 93 号幻灯片不言自明(希望他们不要因为我在这里复制而生我的气).>
以防万一图片被撤下,基本上:
length
总是拉取所有记录,然后在数组上调用 .length - 错误count
总是进行计数查询 - 很好size
如果您有缓存计数器,则查看缓存,否则进行计数查询 - 最好
Assuming there are 2 models called User
and Post
Which will be better performance(fast) either "Plan A" or "Plan B"?
"Plan A"
controller
@users = User.find_all_by_country(params[:country])
@posts = Post.find_all_by_category(params[:category])
view
<%= @users.count.to_s %>
<%= @posts.count.to_s %>
"Plan B"
controller
@users = User.find_all_by_country(params[:country])
@posts = Post.find_all_by_category(params[:category])
view
<%= @users.length.to_s %>
<%= @posts.length.to_s %>
In ruby, count
, length
and size
all do pretty much the same thing regarding arrays. See here for more info.
When using ActiveRecord objects, however, count
is better than length
, and size
is even better.
find_all_by_country
returns a dumb array so you shouldn't use that method (because it always returns an array). Instead, use where(country: params[:country])
.
I'll let Code School's Rails Best Practices slide nº 93 speak for itself (and hope they don't get mad at me for reproducing it here).
Just in case the image gets taken down, basically:
length
always pulls all the records and then calls .length on the array - badcount
always does a count query - goodsize
looks at the cache if you have a cache counter, otherwise does a count query - best
这篇关于哪个更快“计数"?还是“长度"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!