Akshay Mohite
Akshay Mohite

Reputation: 2268

Memoization vs Lazy initialization/evaluation

What is the exact difference between Memoization and lazy initialization technique.

Example with respect to ruby would be great.

Upvotes: 7

Views: 1438

Answers (1)

Erez Rabih
Erez Rabih

Reputation: 15788

Memoization is saving the result of a long execution in order to not repeat it once called again.

An example for memoization:

class A
  def initialize
  end

  def do_some_long_calculation
    @do_some_long_calculation ||= my_calc_here
  end
end

It means that once we call do_some_long_calculation the result would be saved to @do_some_long_calculation and subsequent calls won't trigger the my_calc_here method.

Lazy initialization is making this long execution only when needed and not when initializing the object.

Actually the first code example also demonstrates lazy initialization. A non lazy initialization version would look like:

class A
  def initialize
    @do_some_long_calculation = my_calc_here
  end

  def do_some_long_calculation 
    @do_some_long_calculation 
  end
end

As you can see, here we do the lengthy calculation immediately on the init of class A, whereas in the first example we only do the calculation when the exact method is called.

The long calculation is still done only once, but on the initialization of the class and not when explicitly called.

Upvotes: 8

Related Questions