Skip to content

Instantly share code, notes, and snippets.

@jsphkhan
Created July 28, 2018 11:24
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 jsphkhan/f7c30ec51625f43e6cb33c9f8d1d0c46 to your computer and use it in GitHub Desktop.
Save jsphkhan/f7c30ec51625f43e6cb33c9f8d1d0c46 to your computer and use it in GitHub Desktop.
Perf benchmark for Normal Fibonacci and Fibonacci with Memoization (Dynamic Programming)
//Fibonacci series perf comparisions
//Recursive Call vs Dynamic Programing
//1 1 2 3 5 8 13 21
//normal recursion - O(2^n)
function fibonacci1(seq) {
if(seq === 1 || seq === 2) {
return 1;
}
return fibonacci1(seq - 1) + fibonacci1(seq - 2);
}
var t1 = performance.now();
fibonacci1(20);
var t2 = performance.now();
console.log(t2 - t1);
//Dynamic programming - caching/memoization
var arr = [1,1];
function fibonacci2(seq) {
if(arr[seq - 1]) {
return arr[seq - 1];
}
arr[seq - 1] = fibonacci2(seq - 1) + fibonacci2(seq - 2);
return arr[seq - 1];
}
var t1 = performance.now();
fibonacci2(20);
var t2 = performance.now();
console.log(t2 - t1);
//Dynamic programming >> Normal Recursion
//With normal recursion the browser hangs when you try to fin dout fibonacci(100)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment