Ad space (banner)
๐Ÿ“ŠR Lessons
Lesson 38 / 68

Speeding up calculation with memoization (caching)

This lesson covers memoization in R, with the aim of understanding how to avoid repeating the same calculation.

Memoization stores a result once calculated and, when the same input arrives again, fetches it from storage instead of recalculating. Picture answering a repeated question from memory rather than working it out afresh.

The sample code uses an environment created with new.env() as a cache and checks with exists(key, envir = cache) each time slow_square() is called. From the second identical input onwards you see the "Retrieved from cache" message.

A common early stumble is managing state with an environment. Unlike an ordinary variable, an environment is passed by reference, so its contents can be changed from outside the function.

In professional work, caching recursive calculations and API results gives speed improvements you can feel.

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

๐Ÿงช This site can't compile or run R 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)