哪个更快“计数"?还是“长度"? [英] Which is faster "count" or "length"?

查看:30
本文介绍了哪个更快“计数"?还是“长度"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设有 2 个模型,分别称为 UserPost

A 计划"或B 计划"哪个表现更好(快)?

A 计划"

控制器

@users = User.find_all_by_country(params[:country])@posts = Post.find_all_by_category(params[:category])

查看

<%= @users.count.to_s %><%=@posts.count.to_s %>

B 计划"

控制器

@users = User.find_all_by_country(params[:country])@posts = Post.find_all_by_category(params[:category])

查看

<%= @users.length.to_s %><%=@posts.length.to_s %>

解决方案

在 ruby​​ 中,countlengthsize 都差不多关于数组的同样的事情.请参阅此处了解更多信息.

当使用ActiveRecord对象时,countlength更好,size甚至更好.

find_all_by_country 返回一个哑数组,因此您不应使用该方法(因为它总是返回一个数组).相反,使用 where(country: params[:country]).

我会让 Code SchoolRails 最佳实践第 93 号幻灯片不言自明(希望他们不要因为我在这里复制而生我的气).>

以防万一图片被撤下,基本上:

  1. length 总是拉取所有记录,然后在数组上调用 .length - 错误

  2. count 总是进行计数查询 - 很好

  3. 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:

  1. length always pulls all the records and then calls .length on the array - bad

  2. count always does a count query - good

  3. size looks at the cache if you have a cache counter, otherwise does a count query - best

这篇关于哪个更快“计数"?还是“长度"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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