Skip to content

Instantly share code, notes, and snippets.

@fupslot
Last active August 29, 2015 14:27
Show Gist options
  • Save fupslot/e3fe99498e2647a5c443 to your computer and use it in GitHub Desktop.
Save fupslot/e3fe99498e2647a5c443 to your computer and use it in GitHub Desktop.
Memoization For Improved Application Performance
function memoize(fn) {
fn.memoize || (fn.memoize = {});
return function(arg) {
if (fn.memoize.hasOwnProperty(arg)) {
console.log('memoized //-> %s', arg);
return fn.memoize[arg];
}
else {
console.log('computed //-> %s', arg);
fn.memoize[arg] = fn(arg);
return fn.memoize[arg];
}
};
}
function expensiveCompute(num) {
return num;
}
var compute = memoize(expensiveCompute);
compute(1);
compute(2);
compute(3);
compute(3);
compute(2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment