Skip to content

Instantly share code, notes, and snippets.

@yukidarake
Created September 19, 2013 04:44
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 yukidarake/6619218 to your computer and use it in GitHub Desktop.
Save yukidarake/6619218 to your computer and use it in GitHub Desktop.
クロージャーを利用してキャッシュすると速いよというテク
function fibonacci1(x) {
if (x < 2) {
return 1;
}
return fibonacci1(x - 1) + fibonacci1(x - 2);
}
var fibonacci2 = (function() {
var cache = {};
function fibonacci(x) {
if (x < 2) {
return 1;
}
if (!cache[x]) {
cache[x] = fibonacci(x - 1) + fibonacci(x - 2);
}
return cache[x];
}
return fibonacci;
})();
console.time('fibonacci1');
fibonacci1(33);
console.timeEnd('fibonacci1');
console.time('fibonacci2');
fibonacci2(33);
console.timeEnd('fibonacci2');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment