What is the exact difference between Memoization
and lazy initialization
technique.
Example with respect to ruby would be great.
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.
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