简体   繁体   English

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

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

In my rails app I am fetching a batch of data from the DB with around a million records.在我的 Rails 应用程序中,我从数据库中获取一批数据,其中包含大约一百万条记录。 I am simply calling the following query combined with some pagination logic, and right now it is working very well.我只是结合一些分页逻辑调用以下查询,现在它运行良好。 The code is defined in my model, like so:该代码在我的 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

However, in my previous attempt, I had the following code defined in my model:但是,在我之前的尝试中,我在 model 中定义了以下代码:

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

And I called .offset and .limit inside the controller like so:我在 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

When I did this, my memory completely gave up on the 3rd or 4th page and my app just crashed.当我这样做时,我的 memory 在第 3 或第 4 页完全放弃,我的应用程序刚刚崩溃。 I don't know why calling .limit and .offset in the model solved the issue.我不知道为什么在 model 中调用.limit.offset解决了这个问题。

So my question is, how does calling class methods in your model rather than the controller improve code execution performance?所以我的问题是,如何在 model 而不是 controller 中调用 class 方法来提高代码执行性能? I mean this query is obviously data-related so it makes sense to call it inside the model anyways, but I would still like to know the wonders behind the magic.我的意思是这个查询显然是与数据相关的,所以无论如何在 model 中调用它是有意义的,但我仍然想知道魔法背后的奇迹。

Thank you!谢谢!

how does calling class methods in your model rather than the controller improve code execution performance?在 model 而不是 controller 中调用 class 方法如何提高代码执行性能?

It should not.它不应该。 Both your queries return a ActiveRecord::Relation .您的两个查询都返回ActiveRecord::Relation Both offset and limit are used to build the query, so in both scenarios you should see the same query in your logs. offsetlimit都用于构建查询,因此在这两种情况下,您都应该在日志中看到相同的查询。 Please check your development.log when in doubt.如有疑问,请检查您的development.log

Having the code query code in your model makes sense.在 model 中包含代码查询代码是有意义的。 The controller shouldn't know all those details. controller 不应该知道所有这些细节。

About the pagination, there are a few solutions in the rails world - Kaminari , will_paginate关于分页,rails 世界里有几个解决方案 - Kaminari , will_paginate

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

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