Skip to content

Instantly share code, notes, and snippets.

@mattzeunert
Created August 21, 2015 09:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattzeunert/ba9c638aaa29c77ae05b to your computer and use it in GitHub Desktop.
Save mattzeunert/ba9c638aaa29c77ae05b to your computer and use it in GitHub Desktop.
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