Posted about 7 years ago. Visible to the public.
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 Archive 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
- Speeding up Rails with Memoization Archive
- 4 Simple Memoization Patterns in Ruby (And One Gem) Archive
- Don't use the || operator to set defaults
Exercise
Write a class WebsiteSizer
that measures the number of characters in the given URL's HTML body:
Copywebsite_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
:
- A version that manually caches the results in some Ruby data structure
- A version that caches using the
memoized
gem.
Does your version of Ruby on Rails still receive security updates?
Rails LTS provides security patches for unsupported versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2).