使用 early return 优化基本方法记忆
Optimizing basic method memoization with early return
在 Ruby 中实现基本记忆化时,是否有一种模式或简单的方法来 return 记忆化的实例变量,如果该值预先基于更复杂的评估进行预测?
说 something
的赋值需要大量计算,Ruby 是否足够智能以 return 实例变量(如果存在),或者 something
总是被赋值在设置 @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
什么是更好的记忆模式来实现我所拥有的?
根据您当前编写代码的方式,"intense calculation" 将始终出现。 Ruby 使用隐式 return 除非你显式使用关键字 return
,因此,即使 @some_value
存在,代码仍然会执行到最后一行。
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
因此,如果您想要 return @some_value
(如果它存在),而不是 运行 之后的任何代码,您将需要使用显式 return。见上文。
现在,Ruby 将检查 @some_value
是否存在,如果是 true
,则值为 returned,否则,它将继续计算。
在 Ruby 中实现基本记忆化时,是否有一种模式或简单的方法来 return 记忆化的实例变量,如果该值预先基于更复杂的评估进行预测?
说 something
的赋值需要大量计算,Ruby 是否足够智能以 return 实例变量(如果存在),或者 something
总是被赋值在设置 @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
什么是更好的记忆模式来实现我所拥有的?
根据您当前编写代码的方式,"intense calculation" 将始终出现。 Ruby 使用隐式 return 除非你显式使用关键字 return
,因此,即使 @some_value
存在,代码仍然会执行到最后一行。
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
因此,如果您想要 return @some_value
(如果它存在),而不是 运行 之后的任何代码,您将需要使用显式 return。见上文。
现在,Ruby 将检查 @some_value
是否存在,如果是 true
,则值为 returned,否则,它将继续计算。