每个或find_each?还是需要 smart_each? [英] each or find_each? Or need smart_each?

查看:25
本文介绍了每个或find_each?还是需要 smart_each?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的代码:

User.any_scope.each do |user|
  user.do_anything
end 

如果我有大量用户:

User.any_scope.find_each do |user|
  user.do_anything
end

如果用户数<100:

使用 find_each 对性能来说不是一个好主意

it is not good idea for perfomance to use find_each

这样的代码怎么样:

def smart_each_for(user)
  MAX_COUNT = 100
  user.count > MAX_COUNT ? 'find_each' : 'each'  # 100 - 
end

smart_each = smart_each_for(User.any_scope)

User.any_scope.send :smart_each do |user|
  user.do_anything
end

这对性能来说是个好主意吗?MAX_COUNT 呢?这个变量应该有什么值?

It is good idea for perfomance? What about MAX_COUNT ? What value should this variable have?

推荐答案

查看find_each 方法:

注意:无法设置顺序.那是自动设置为在主键(id ASC")上升序以进行批量排序工作.这也意味着此方法仅在主键是可排序的(例如整数或字符串).

NOTE: It's not possible to set the order. That is automatically set to ascending on the primary key ("id ASC") to make the batch ordering work. This also means that this method only works when the primary key is orderable (e.g. an integer or string).

注意:您也不能设置限制,用于控制批处理尺寸.

NOTE: You can't set the limit either, that's used to control the batch sizes.

注意:就其性质而言,批处理会受到竞争条件的影响,如果其他进程正在修改数据库.

NOTE: By its nature, batch processing is subject to race conditions if other processes are modifying the database.

注意:此方法仅用于批处理大量记录无法一次性全部放入内存.如果你只需要循环少于 1000 条记录,它可能是最好使用常规的 find 方法.

Note: This method is only intended to use for batch processing of large amounts of records that wouldn’t fit in memory all at once. If you just need to loop over less than 1000 records, it’s probably better just to use the regular find methods.

所以不,在您提供的示例中使用它不是一个好主意.

So no, it is not a good idea to use it in the examples you provided.

这篇关于每个或find_each?还是需要 smart_each?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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