Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memoization vs Lazy initialization/evaluation

Tags:

ruby

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

Example with respect to ruby would be great.

like image 885
Akshay Mohite Avatar asked Oct 12 '14 05:10

Akshay Mohite


1 Answers

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.

like image 191
Erez Rabih Avatar answered Oct 07 '22 18:10

Erez Rabih