Ad space (banner)
🟨JavaScript Lessons
Lesson 39 / 69

Speeding Up Calculations with Memoization (Caching)

In this lesson you'll learn the technique of memoization (caching) so you can speed up heavy calculations efficiently. This is for people searching "JavaScript what is memoization" or "JavaScript how to implement caching."

Memoization is a technique where you save a calculation's result in a "storage box" once, so if the same input comes in again, you just pull it out of the box instead of recalculating. Picture it like "if you're asked the same question every time, you just give back the answer you already remember." Since you no longer need to repeat a heavy, time-consuming calculation over and over, this can dramatically improve an app's response speed.

The sample code uses an object called cache as the storage box, checking "has this already been calculated" with the in operator inside the slowSquare function. If it's already calculated, it returns the value from the cache immediately; if not, it calculates first, then saves the result into the cache. Check how the display differs the two times 5 is passed in.

A common beginner stumbling block is figuring out what to use as the cache key. For a function with multiple arguments, you need some approach like combining them into a single string to use as the key. Also, using the cache too aggressively keeps consuming memory forever, so real projects need some way to avoid storing an unlimited amount.

The heavier the numerical computation, the bigger the effect, and this idea is commonly used in real-world performance improvements. The idea of memoization is also applied to things like caching network requests, to avoid sending the same API request over and over.

JavaScript
OUTPUT

💡 Anything passed to console.log() appears in the output below.

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