Seth
Seth

Reputation: 10454

Optimizing basic method memoization with early return

When implementing basic memoization in Ruby, is there a pattern or simple way to return the memoized instance var if the value predicates on a more complex evaluation before hand?

Say the assignment of something requires an intense calculation, is Ruby smart enough to return the instance variable if it's present, or will something always be assigned within the scope of that method before setting @some_value?

  def some_value
    @some_value if @some_value.present? # possible?
    something = something_else.try(:method_name) || another_something.method_name # prevent this from evaluating after execution
    @some_value ||= MyClass.new(property: something.property)
  end

What would a better memoization pattern be to implement what I have?

Upvotes: 2

Views: 257

Answers (1)

davidhu
davidhu

Reputation: 10452

Based on how your code is currently written, the "intense calculation" will always occur. Ruby uses implicit return unless you explicitly use the keyword return, so, even if @some_value is present, the code will still execute to the last line.

def some_value
  return @some_value if @some_value.present? # possible?
  something = something_else.try(:method_name) || another_something.method_name # prevent this from evaluating after execution
  @some_value ||= MyClass.new(property: something.property)
end

So, if you want to return @some_value if it is present, and not run any code afterwards, you will want to use explicit return. See above.

Now, Ruby will check if @some_value is present, and if that is true, the value is returned, otherwise, it will continue with the calculation.

Upvotes: 2

Related Questions