Skip to content

Instantly share code, notes, and snippets.

@psiphi75
Created November 28, 2018 22:25
Show Gist options
  • Save psiphi75/867d285f5062ac952dcd3524155332db to your computer and use it in GitHub Desktop.
Save psiphi75/867d285f5062ac952dcd3524155332db to your computer and use it in GitHub Desktop.
function memoize(fn) {
return function() {
var args = Array.prototype.slice.call(arguments);
fn.cache = fn.cache || {};
return fn.cache[args]
? fn.cache[args]
: (fn.cache[args] = fn.apply(this, args));
};
}
function sqrt(arg) {
let result = 0.0;
for (let i = 0; i < 1000000; i += 1) result += Math.sqrt(arg);
return result;
}
const memoizedSqrt = memoize(sqrt);
console.time('memoized call');
memoizedSqrt(4);
console.timeEnd('memoized call'); // 10.461ms
console.time('non-memoized call');
memoizedSqrt(4);
console.timeEnd('non-memoized call'); // 0.022ms
console.time('Direct call');
sqrt(4);
console.timeEnd('Direct call'); // 6.855ms
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment