繁体   English   中英

在 model 与 controller 中调用 class 方法时的性能差异?

[英]Performance difference when calling class methods in model vs controller in rails?

在我的 Rails 应用程序中,我从数据库中获取一批数据,其中包含大约一百万条记录。 我只是结合一些分页逻辑调用以下查询,现在它运行良好。 该代码在我的 model 中定义,如下所示:

def find_records(current_page, max_records, start_value, end_value)
   where(value_range: start_value..end_value)
        .offset((current_page - 1) * max_records).limit(max_records)
end

但是,在我之前的尝试中,我在 model 中定义了以下代码:

def find_records(max_records, start_value, end_value)
   where(value_range: start_value..end_value)
end

我在 controller 中调用了.offset.limit ,如下所示:

def index
  current_page = params[:page]
  max_records = 3
  start_value = 4
  end_value = 8
  Model.find_records(start_value, end_value).offset((current_page - 1) * max_records).limit(max_records)
end

当我这样做时,我的 memory 在第 3 或第 4 页完全放弃,我的应用程序刚刚崩溃。 我不知道为什么在 model 中调用.limit.offset解决了这个问题。

所以我的问题是,如何在 model 而不是 controller 中调用 class 方法来提高代码执行性能? 我的意思是这个查询显然是与数据相关的,所以无论如何在 model 中调用它是有意义的,但我仍然想知道魔法背后的奇迹。

谢谢!

在 model 而不是 controller 中调用 class 方法如何提高代码执行性能?

它不应该。 您的两个查询都返回ActiveRecord::Relation offsetlimit都用于构建查询,因此在这两种情况下,您都应该在日志中看到相同的查询。 如有疑问,请检查您的development.log

在 model 中包含代码查询代码是有意义的。 controller 不应该知道所有这些细节。

关于分页,rails 世界里有几个解决方案 - Kaminari , will_paginate

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM