This code takes 3 seconds on Chrome and 6s on Firefox.
If I write the code in Java and run it under Java 7.0 it takes only 10ms.
Chrome’s JS engine is usually very fast. Why is it so slow here?
btw. this code is just for testing. I know it’s not very practical way to write a fibonacci function
fib = function(n) {
if (n < 2) {
return n;
} else {
return fib(n - 1) + fib(n - 2);
}
};
console.log(fib(32));
This isn’t fault of javascript, but your algorithm. You’re recomputing same subproblems over and over again, and it gets worse when N is bigger. This is call graph for a single call:
As you can see from this tree, you’re computing some fibonacci numbers several times, for example F(28) is computed 4 times. From the “Algorithm Design Manual” book:
You have to use memoization or build solution bottom up (i.e. small subproblems first).
This solution uses memoization (thus, we’re computing each Fibonacci number only once):
This one solves it bottom up: