Created
March 29, 2016 14:01
-
-
Save jabranr/203495c5520aec757921 to your computer and use it in GitHub Desktop.
JavaScript optimization example using console.time
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
/** | |
* @link http://adripofjavascript.com | |
*/ | |
// Example 1 | |
(function(console) { | |
function factoral(num) { | |
if (num < 0) throw new Error('Bad input!'); | |
if (num % 1 !== 0) throw new Error('That\'s NaN!'); | |
if (num === 0 || num === 1) return 1; | |
return num * factoral(num - 1); | |
} | |
console.time('foo'); | |
for(var i = 0; i < 100; i++) { factoral(20); } | |
console.timeEnd('foo'); | |
})(window.console); | |
// Example 2 - Optimized | |
(function(console) { | |
function factoral(num) { | |
if (num < 0) throw new Error('Bad input!'); | |
if (num % 1 !== 0) throw new Error('That\'s NaN!'); | |
if (num === 0 || num === 1) return 1; | |
function inception(n) { | |
if (n === 0 || n === 1) return 1; | |
return n * inception(n - 1); | |
} | |
return inception(num); | |
} | |
console.time('bar'); | |
for(var i = 0; i < 100; i++) { factoral(20); } | |
console.timeEnd('bar'); | |
})(window.console); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment