Skip to content

Instantly share code, notes, and snippets.

@marcheiligers
Created February 21, 2012 10:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marcheiligers/1875604 to your computer and use it in GitHub Desktop.
Save marcheiligers/1875604 to your computer and use it in GitHub Desktop.
JS Memoization
// Simple memoization which only handles a single argument
// There's lots of things wrong with this code,
// like that it doesn't handle falsy values, for example.
// See below for a good discussion on memoization:
// http://addyosmani.com/blog/faster-javascript-memoization
Function.prototype.memoize = function() {
var fn = this,
cache = {};
return function(arg) {
if(!cache[arg]) {
cache[arg] = fn.call(null, arg);
}
return cache[arg];
};
};
function fibonaci(n) {
return n < 2 ? 1 : fibonaci(n - 1) + fibonaci(n - 2);
}
function beersOnAWall(n) {
return console.log(fibonaci(n) + " beers on a wall...");
}
var d = new Date();
beersOnAWall(25);
console.log((new Date().getTime() - d.getTime()) + "ms");
fibonaci = fibonaci.memoize();
d = new Date();
beersOnAWall(25);
console.log((new Date().getTime() - d.getTime()) + "ms");
// 121393 beers on a wall...
// 128ms
// 121393 beers on a wall...
// 1ms
// ...with 32...
// 3524578 beers on a wall...
// 3725ms
// 3524578 beers on a wall...
// 2ms
// ...with 35 the non-memoized received script timeouts
// 14930352 beers on a wall...
// 2ms
// ...1000?!?...
// 7.0330367711422765e+208 beers on a wall...
// 4ms
// That's a lot of beer.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment