Reputation: 250
As we all know in Ruby, the last line of a method is the "returned" value of that method.
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.
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?
def test_method
some_big_object
end
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?
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. But purely speaking of performance, am I correct?
Upvotes: 3
Views: 210
Reputation: 80075
Any method will return an object, or more specific: an object_id, which is just a number. Nil, false, some_big_object : all just a number. Don't bother.
Upvotes: 2