Last active
August 29, 2015 13:57
-
-
Save davestevens/9782498 to your computer and use it in GitHub Desktop.
JS For Loops?
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
// Setup | |
var array = []; | |
for(var i = 0; i < 1000; ++i) { array.push(i); } | |
var totals = {}; | |
var log = function (id, time) { | |
totals[id] = totals[id] ? totals[id] : []; | |
totals[id].push(time); | |
}; | |
var mean = function(array) { | |
var total = 0; | |
$.each(array, function (_, element) { | |
total += element; | |
}); | |
return (total / array.length); | |
}; | |
var display_totals = function () { | |
var i; | |
$.each(totals, function(index, element) { | |
// sum them up and divide by length | |
console.log(mean(element)); | |
}); | |
}; | |
var benchmark = function (id, callback) { | |
var diff, start = window.performance.now(); | |
callback.apply(this); | |
diff = window.performance.now() - start; | |
log(id, diff); | |
}; | |
var run = function () { | |
benchmark(1, function() { var i, length = array.length; for (i = 0; i < length; ++i) { } }); | |
benchmark(2, function() { $(array).each(function(index, element) { }); }); | |
benchmark(3, function() { $.each(array, function(index, element) { }); }); | |
} | |
// Run multiple times and display mean time | |
var i, num = 100; | |
for(i = 0; i < num; ++i ) { | |
run(); | |
} | |
display_totals(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment