Skip to content

Instantly share code, notes, and snippets.

@psiphi75
Last active November 28, 2018 22:19
Show Gist options
  • Save psiphi75/db2fd823a3e01ac8d87a83811ecc33d2 to your computer and use it in GitHub Desktop.
Save psiphi75/db2fd823a3e01ac8d87a83811ecc33d2 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) {
return Math.sqrt(arg);
}
const memoizedSqrt = memoize(sqrt);
console.time('Do nothing');
// do nothing
console.timeEnd('Do nothing'); // 0.064ms
console.time('memoized call');
memoizedSqrt(4);
console.timeEnd('memoized call'); // 0.157ms
console.time('non-memoized call');
memoizedSqrt(4);
console.timeEnd('non-memoized call'); // 0.015ms
console.time('Direct, no caching');
sqrt(4);
console.timeEnd('Direct, no caching'); // 0.003ms - I guess this is mostly `console.time`
console.time('Direct, no caching');
sqrt(4);
console.timeEnd('Direct, no caching'); // 0.002ms
console.time('Direct, no caching');
sqrt(4);
console.timeEnd('Direct, no caching'); // 0.001ms
console.time('Do nothing');
// do nothing
console.timeEnd('Do nothing'); // 0.001ms - compare this with the first 'Do nothing'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment