This question is mostly about Ruby internals, the speed can be gauged with a simple benchmark.
What's the most efficient way to memoize a return value in ruby?
I've always memoized values with:
def method
@value ||= calculate_value
end
But since it technically expands to:
@value = @value || calculate_value
I wonder about the efficiency of re-executing the same assignment each time.
Would this be better?
def method
@value ? @value : (@value = calculate_value)
end
Also, does it change in different interpreters? MRI, Rubinius, etc.
Memoization is a technique you can use to speed up your accessor methods. It caches the results of methods that do time-consuming work, work that only needs to be done once. In Rails, you see memoization used so often that it even included a module that would memoize methods for you.
Put simply, memoization is saving a method's return value so it does not have to be recomputed each time. As with all caching, you are effectively trading memory for time (i.e. you give up the memory required to store the value, but you save the time required to process the method).
In programming, memoization is an optimization technique that makes applications more efficient and hence faster. It does this by storing computation results in cache, and retrieving that same information from the cache the next time it's needed instead of computing it again.
In computing, memoization or memoisation is an optimization technique used primarily to speed up computer programs by storing the results of expensive function calls and returning the cached result when the same inputs occur again.
Your example
@value ||= calculate_value
is equivalent to
@value || @value = calculate_value
and is not equivalent to
@value = @value || calculate_value
Therefore the answer is: It is very efficient. It is not re-assigned each time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With