为什么Rails为每个请求创建一个控制器? [英] Why does Rails create a controller for every request?

查看:124
本文介绍了为什么Rails为每个请求创建一个控制器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从我之前的问题,我了解到Rails会为每个请求创建一个控制器实例。

From my previous question I understood that Rails creates a controller instance for every request.

我的问题是,因为这个主题与我正在开发的项目的设计有关:

My question is, because this subject is related to the design of the project I'm working on:

为什么Rails创建一个新的实例

Why does Rails creates a new instance of

class SomeController < ApplicationController; end

来处理每个传入的请求?为什么不只是创建单例对象和转发请求到这一个?这似乎更有效,因为我们不会浪费资源分配和清理对象的请求?

to process every incoming request? Why not just create singleton object and forward requests to this one? This seems more efficient as we won't waste resources on allocating and cleaning objects for request?

推荐答案

实例化新控制器实例的开销并不重要,这意味着两个完全不相关的请求之间没有意外的共享状态。处理器时间中的任何节省都将被产生毁灭性错误的潜力所抵消。

The overhead of instantiating a new controller instance is insignificant, and it means there is no accidentally shared state between two completely unrelated requests. Any "savings" in processor time would be more than offset by the potential to produce devastating bugs.

请记住,控制器用于存储请求特定状态。重新使用控制器将需要你重置每个 @variable 你在每个动作开始时设置。否则,像 @is_admin = true 的东西可能被设置为未清除。

Remember that controllers are for storing request-specific state. Reusing controllers would require you to reset every @variable you'd ever set, at the start of every action. Otherwise, something like @is_admin = true could wind-up being set and never cleared. The less contrived bugs you'd actually be introducing would be much more subtle and draining on developer time.

你可以看到没有任何优化的优化。 必须保持状态并在请求之间重置,或者您有这个噩梦意外共享的状态。如果您在请求之间保留控制器实例,那么您只是将维护/重置状态的作业推迟到某个较低的级别,其中的答案可能仍然是实例化一些新的状态管理实例类。在分配和释放资源时,计算机是非常好的,因此在你真正知道它是一个瓶颈之前,永远不要担心这个问题。 在这种情况下,为每个请求实例化一个新的控制器很容易是正确的选择。

You're seeing optimizations where there are none. Something must maintain state and reset it between requests, or you have this nightmare of accidentally shared state. If you persist controller instances between requests, you're simply pushing the job of maintaining/resetting state down to some lower level, where the answer will likely still be to instantiate a fresh instance of some state-managing class for each request. Computers are very good at allocating and freeing resources, so never worry about that until you actually know it's a bottleneck. In this case, instantiating a new controller for each request is easily the correct choice.

在Rails的情况下,能够使用 @variable = value 是代码清晰度和可用性立场的主要胜利,并且这或多或少必须在请求完成时丢弃控制器的每个实例。

In the case of Rails, being able to use @variable = value is a major win from a code-clarity and usability stand-point, and this more or less necessitates discarding each instance of a controller when the request completes.

这篇关于为什么Rails为每个请求创建一个控制器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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