简体   繁体   English

在方法结束时返回nil或boolean比让Ruby返回最后一行代码的结果更高效吗?

[英]Is returning nil or a boolean at the end of a method more performant than letting Ruby return the result of the last line of code?

As we all know in Ruby, the last line of a method is the "returned" value of that method. 众所周知,在Ruby中,方法的最后一行是该方法的“返回”值。

Let's say you have a procedure (aka, a method where we just want it to do work and do not care about the return value) that builds a heavy object, or its last line is a Rails logger statement or some other class instance. 假设你有一个程序(也就是我们只是希望它工作而不关心返回值的方法)构建一个繁重的对象,或者它的最后一行是一个Rails记录器语句或一些其他类实例。

Is it more performant (or consume less resources somehow), if you just add a "nil" or "boolean" to the last line instead of returning that heavy object when we don't use that return value? 如果你只是在最后一行添加“nil”或“boolean”而不是在我们不使用该返回值时返回那个重的对象,它是否更具性能(或以某种方式消耗更少的资源)?

def test_method
    some_big_object
end

vs VS

def test_method
    some_big_object
    nil # or true/false
end

In my mind, as far as pure object allocation, memory performance goes, the first option is better. 在我看来,就纯对象分配而言,内存性能越高,第一种选择就越好。 Just because the method "returns" a big object that isn't used, doesn't mean it takes any further processing or causes any extra memory bloat. 仅仅因为该方法“返回”一个未使用的大对象,并不意味着它需要进一步处理或导致任何额外的内存膨胀。

The second option seems like it is actually ever so slightly worse due to the fact that it now creates one additional object. 第二种选择似乎实际上是因为它现在创建了一个额外的对象。

I feel like adding the extra return line, especially if that return line is something other than nil, is redundant and wasteful. 我想添加额外的返回线,特别是如果返回线不是零,则是多余的和浪费的。 Surely Ruby's, and even JRUBY's, garbage collection is smarter than that? 当然Ruby,甚至是JRUBY,垃圾收集比这更聪明?

I do realize there may be some benefit in returning nil to prevent other developers from trying to use this method to return a value when it is only meant to do work. 我确实意识到返回nil可能会有一些好处,以防止其他开发人员尝试使用此方法返回值时,只是为了工作。 But purely speaking of performance, am I correct? 但纯粹谈到表现,我是否正确?

Any method will return an object, or more specific: an object_id, which is just a number. 任何方法都将返回一个对象,或者更具体:object_id,它只是一个数字。 Nil, false, some_big_object : all just a number. Nil,false,some_big_object:只是一个数字。 Don't bother. 不要打扰。

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

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