Created
February 21, 2012 10:10
-
-
Save marcheiligers/1875604 to your computer and use it in GitHub Desktop.
JS Memoization
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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