Memoization In JavaScript

Example

const sum = (a, b) => a + b;
console.log(sum(2,7))
console.log(sum(2,7))
//output: 9
//output: 9
const cache = {
"2,7":9
}

Complexity

var cachedResult;
function doHeavyCalculation()
{
if (typeof(cachedResult) !== 'undefined')
return cachedResult;

// no cached result available. calculate it, and store it.
cachedResult = /* do your computation */;
return cachedResult;
}

The Fibonacci Series

function fib( x ) {
if(x < 2) return 1; else return fib(x-1) + fib(x-2);
}

/*console profiling test*/
var fibTest = memoize(fib);
//first call
console.time("non-memoized call");
console.log(fibTest(20)); //varies (eg.10946)
console.timeEnd("non-memoized call");

//let's see how much better memoization fares..
console.time("memoized call");
console.log(fibTest(20));
//0ms in most cases (if already cached)
console.timeEnd("memoized call");

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Soner Mezgitci

Soner Mezgitci

31 Followers

Software Engineer | Ruby on Rails | JavaScript | HTML5 | CSS | PostgreSQL | React | Redux