Skip to content

Instantly share code, notes, and snippets.

@abiodun0
Last active July 17, 2020 14:19
Show Gist options
  • Save abiodun0/fd7062afd5a1c68243736563de6d5fb0 to your computer and use it in GitHub Desktop.
Save abiodun0/fd7062afd5a1c68243736563de6d5fb0 to your computer and use it in GitHub Desktop.
Estimates the time difference in performance for recursive and iterative function in javascript. Using finabocci as a case study
recurse :: (Integral a) -> a -> a
recurse 1 = 1
recurse 0 = 1
recurse n = recurse (n-2) + recurse (n-1)
-- refactoring
recurse :: (Integral a) -> a -> a
recurse n
| n < 2 = 1
| otherwise = recurse (n-2) + recurse (n-1)
function recurse(n) {
if (n < 2) return 1;
return recurse(n - 2) + recurse(n - 1);
}
// O(fib(n)) = O(φ^n) (φ = (1+√5)/2);
function iterate(n) {
if(n <= 1) {
return n;
}
var fib = 1;
var prevFib = 1;
for(var i=1; i<n; i++) {
var temp = fib;
fib+= prevFib;
prevFib = temp;
}
return fib;
}
function memoizedRecurse() {
memoizedValue = {};
return function recurse(n){
if(memoizedValue[n]) return memoizedValue[n];
if (n < 2) return 1;
f = recurse(n - 2) + recurse(n - 1);
memoizedValue[n] = f;
return f;
}
}
function perf(times, func, msg) {
const start = Date.now();
for (let i = 0; i <= times; ++i) {
func();
}
console.log(msg, 'Time taken to complete:', Date.now() - start, 'ms');
}
x = memoizedRecurse()
perf(10000000, () => recurse(10), 'Recursion');
perf(10000000, () => iterate(10), 'Iterative');
perf(10000000, () => x(10), 'memoizedRecursion');
@anubabajide
Copy link

Care to drop the Runtime Results?

@abiodun0
Copy link
Author

You can simpy run the code on any browser to figure that out

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment