Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby memoization, efficiency

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.

like image 541
tompave Avatar asked Oct 25 '14 10:10

tompave


People also ask

What is memoization in Ruby?

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.

How does memoization work in Rails?

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).

What is memoization why and when would you use it?

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.

What is a Memoized value?

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.


1 Answers

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.

like image 116
spickermann Avatar answered Oct 19 '22 18:10

spickermann