Memoization [0.4d]

Goals

  • Understand what Memoization is and when it can be useful.
  • Understand the @variable ||= computation pattern.
  • Learn how to use the memoized Show archive.org snapshot gem.
  • What are the advantages of a gem like memoized over the @variable ||= syntax?
  • Why can it be dangerous to memoize class methods?
    Why is it often fine to memoize instance methods?

Resources

Exercise

Write a class WebsiteSizer that measures the number of characters in the given URL's HTML body:

website_sizer = WebsiteSizer.new
website_sizer.size_of('https://makandra.com') # => 27448
website_sizer.size_of('https://railslts.com') # => 2145364

You can use any library to perform the actual HTTP request.

The class should cache its results so subsequent calls for the same URLs return the HTML size instantly, without making an additional HTTP request.

Write two versions of WebsiteSizer:

  1. A version that manually caches the results in some Ruby data structure
  2. A version that caches using the memoized gem.
Henning Koch Almost 9 years ago