Ad space (banner)
๐ŸŽฏKotlin Lessons
Lesson 38 / 68

Speeding Up Calculations with Memoization (Caching)

In this lesson you will learn how to speed up calculations with memoization in Kotlin, so the same work is not repeated. This is for anyone searching for "Kotlin memoization how to use".

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 stores computed results in a mutableMapOf called cache, and each time slowSquare() runs it checks whether the answer is already known with cache[n]?.let { ... }. On the second call with the same input you see "Retrieved from cache".

A common stumbling block for beginners is the ?.let { } form itself. It is one of Kotlin's null-safe idioms - run this work only if the value is not null - and it replaces an if statement concisely.

In real-world development, recursive calculations and cached API responses in particular show a speed-up you can feel, making this a familiar idea in performance work.

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

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