Ad space (banner)
๐ŸŸฃJulia Lessons
Lesson 38 / 68

Speeding up calculation with memoization (caching)

This lesson covers memoization in Julia, 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 a typed dictionary, Dict{Int, Int}(), as the cache and checks with haskey(cache, n) each time slow_square() is called. From the second identical input onwards you see the "Retrieved from cache" message.

A common early stumble is specifying the dictionary's type parameters. Stating them, as in Dict{Int, Int}(), lets Julia's compiler optimise and speeds the program up.

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 Julia 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)