Skip to content

Instantly share code, notes, and snippets.

@JackyYin
Created July 10, 2019 06:44
Show Gist options
  • Save JackyYin/f4ba59ebe973472c320b4b4bb6edb8c1 to your computer and use it in GitHub Desktop.
Save JackyYin/f4ba59ebe973472c320b4b4bb6edb8c1 to your computer and use it in GitHub Desktop.
recursion v.s. iteration
const recursion = n => {
if (n === 0) return 0;
if (n === 1) return 1;
return recursion(n - 1) + recursion(n - 2);
};
const iteration = n => {
if (n === 0) return 0;
if (n === 1) return 1;
let prev = 0;
let cur = 1;
let newCur;
for (let i = 2; i < n + 1; i++ ) {
newCur = prev + cur;
prev = cur;
cur = newCur;
}
return cur;
};
const test = input => {
let start;
let time;
start = Date.now();
recursion(input);
time = Date.now() - start;
console.log(time);
start = Date.now();
iteration(input);
time = Date.now() - start;
console.log(time);
}
test(45);
// 13392
// 0
test(46);
// 21487
// 2
test(47);
// 34554
// 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment