DEV Community

Nikunj R. Prajapati
Nikunj R. Prajapati

Posted on

Day 4 : What is memoization in javascript ?

  • Memoization is a cache technique that makes application performance faster by storing the results of expensive function calls.

  • In simple terms it's storing in memory, let's understand it this way,

Example

function someIntensiveDBTask(dependsOnThis){

// Lot's of calculations here, will return same output for same input

}
Enter fullscreen mode Exit fullscreen mode

So in that kind of scenario we can implement Memoization, Let's understand it.

const memo = []
function someIntensiveDBTask(dependsOnThis){

if(memo[dependsOnThis]) return memo[dependsOnThis];

// else part
// Do some calculations...
// ..
// ..
// ..

// we are caching result before returning here and storing it in memo so next time we can use it directly.

memo[dependsOnThis] = result; 

return result

}
Enter fullscreen mode Exit fullscreen mode

Memoization is a way to lower a function’s time cost in exchange for space cost.

Resources :
Res 1
Res 2

Top comments (0)