Last active
August 19, 2016 08:38
-
-
Save akofman/16b39d9e039e83087658 to your computer and use it in GitHub Desktop.
JS Memoization example.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//To run this example : node memoization.js | |
'use strict' | |
var start, result, end; | |
var fibo = function fibonacci(n) { | |
if (n < 2) { | |
return n; | |
} else { | |
return fibonacci(n - 1) + fibonacci(n - 2) | |
} | |
}; | |
var memoFibo = (function fibonacci() { | |
var memo = [0, 1]; | |
return function fib(n) { | |
var result = memo[n]; | |
if (typeof result !== 'number') { | |
result = fib(n - 1) + fib(n - 2); | |
memo[n] = result; | |
} | |
return result; | |
}; | |
})(); | |
start = process.hrtime(); | |
result = fibo(40); | |
end = process.hrtime(start); | |
console.info("fibo result : %s - Execution time : %ds %dms", result, end[0], end[1]/1000000); | |
start = process.hrtime(); | |
result = memoFibo(40); | |
end = process.hrtime(start); | |
console.info("memoFibo result : %s - Execution time : %ds %dms", result, end[0], end[1]/1000000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment