Ad space (banner)
๐Ÿ’ŽRuby Lessons
Lesson 38 / 68

Speeding Up Calculations with Memoization (Caching)

In this lesson you will learn the memoization technique so you can speed up expensive calculations efficiently. This is for anyone searching for "what is Ruby memoization".

Memoization stores a result once it has been computed and returns it straight from storage the next time the same input arrives. Picture being asked the same question repeatedly and simply repeating the answer you remembered.

The sample code uses the hash cache as that storage and checks whether the answer is already known with cache.key?(n) inside slow_square. If it is, the value comes straight back from the cache; if not, it is computed and then stored.

A common stumbling block for beginners is the design of passing the cache in explicitly as an argument. Keeping the cache outside the method and passing it in handles the outer state safely - a safer design than reaching for a global variable.

It is also the classic time/space trade-off: spending memory to save computation time. Recursive calculations and cached API responses in particular show a speed-up you can feel.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Ruby directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)