Menu

Memoization in JavaScript: Cache Results and Speed Things Up
📰

Memoization in JavaScript: Cache Results and Speed Things Up

DEV Community: frontend·Arhan Khan·1 day ago
#ut0cjl95
#devtofrontend#devto#dev#cache#function
Long article (320 words) — no AI summary yet.
Reading 0:00
15s threshold

Some functions are expensive — a heavy calculation, a big search, a complex filter. If you call them twice with the same input, you get the same output, so why compute it twice? Memoization remembers past results and returns the cached answer instead of recalculating.

function memoize ( fn ) { const cache = new Map ( ) ; return function ( . . . args ) { const key = JSON . stringify ( args ) ; if ( cache . has ( key ) ) { return cache . get ( key ) ; } const result = fn ( . . . args ) ; cache . set ( key , result ) ; return result ; } ; }

function slowSquare ( n ) { console . log ( 'Computing...' ) ; return n * n ; }

const fastSquare = memoize ( slowSquare ) ; console . log ( fastSquare ( 5 ) ) ; // Computing... 25 console . log ( fastSquare ( 5 ) ) ; // 25 (from cache, no computing)

Enter fullscreen mode

Exit fullscreen mode

Memoization only works for pure functions — same input, same output, no side effects.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.