Skip to content

Instantly share code, notes, and snippets.

@TheIronDev
Last active May 17, 2016 01:25
Show Gist options
  • Save TheIronDev/8e4d356c0881ea0067ac3c414af06a82 to your computer and use it in GitHub Desktop.
Save TheIronDev/8e4d356c0881ea0067ac3c414af06a82 to your computer and use it in GitHub Desktop.
Comparing times of getting fibonacci number with different method
function fibo(n) {
if (n <= 1) return n;
return fibo(n-1) + fibo(n-2);
}
function tailFibo(n, tail) {
if (n <= 1) return n;
if (tail[n]) return tail[n];
tail[n] = tailFibo(n-1, tail) + tailFibo(n-2, tail);
return tail[n];
}
function itrFibo(n) {
var prev = 0, cur = 1, total = 0, temp;
while(n--) {
prev = cur;
temp = total;
total += cur;
cur = temp;
}
return total;
}
function testAllThree(n) {
var results = {}, time;
time = Date.now();
fibo(n);
results.fibo = Date.now() - time;
time = Date.now();
tailFibo(n, {});
results.tailFibo = Date.now() - time;
time = Date.now();
itrFibo(n);
results.itrFibo = Date.now() - time;
return results;
}
testAllThree(30);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment