Created
August 21, 2015 09:37
-
-
Save mattzeunert/ba9c638aaa29c77ae05b to your computer and use it in GitHub Desktop.
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
var REPEATS = 1000; | |
var _add = function (n1, n2) { | |
return n1 + n2; | |
} | |
a = 4; | |
b = 5; | |
var alternatives = [ | |
{ | |
name: "No function call", | |
action: function (){ | |
var c; | |
for (var i = 0; i < 10000000; i++) { | |
c = a + i; | |
} | |
} | |
}, | |
{ | |
name: "Function call", | |
action: function (){ | |
var c; | |
var add = _add; | |
for (var i = 0; i < 10000000; i++) { | |
c = add(a,i); | |
} | |
} | |
} | |
]; | |
alternatives.forEach(function(alternative){ | |
var start = new Date(); | |
var repeat = REPEATS; | |
for (var i=0; i< repeat;i++) { | |
alternative.action(); | |
} | |
var end = new Date(); | |
var totalMs = end.valueOf() - start.valueOf(); | |
var averageMs = totalMs/repeat; | |
var result = alternative.name + " took " + averageMs + "ms - (" + repeat + " times, total time: " + totalMs + "ms)"; | |
if (typeof console !== "undefined") { | |
console.log(result); | |
} | |
if (typeof document !== "undefined"){ | |
document.body.innerHTML += result + "<br>"; | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment