Skip to content

Latest commit

 

History

History
65 lines (52 loc) · 1.38 KB

Memoization in JavaScript.md

File metadata and controls

65 lines (52 loc) · 1.38 KB

Memoization in JavaScript

[reference link](reference link)

function meoize(fn) {
  return function (...args) {
    fn.cache = fn.cache || {};
    return fn.cache[args] 
      		 ? fn.cache[args] 
    			 : (fn.cache[args] = fn.apply(this.args);
  }
}

// usage
memoizedFunction = memoize(functionToMemoize);
memoizedFunction(args);

Function.prototype.memoize = function () {
  var self = this;
  return function (...args) {
    self.cache = self.cache || {};
    return self.cache[args] 
    			 ? self.cache[args]
    			 : (self.cache[args] = self(args));
  }
}
// usage
memoizedFunction = functionToMemoize.memoize();
memoizedFunction(args)

When To Use

  • Memoization should be implemented on pure functions
  • Memoization wroks best when dealing with recursive functions which are used to perform heavy operations like GUI rendering, Sprit and animations physics, etc
Demo
function sqrt(arg) {
  return Math.sqrt(arg);
}
const memoizedSqrt = memoize(sqrt);
console.log("non-memoized call");
console.log(memoizedSqrt(4));
console.timeEnd("non-memoized call");
console.time("memoized call");
console.log(memoizedSqrt(4));
console.timeEnd("memoized call");
result
$ node memoize
2
non-memoized call: 8.958ms
2
memoized call: 1.298ms