Skip to content

Instantly share code, notes, and snippets.

@davestevens
Last active August 29, 2015 13:57
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 davestevens/9782498 to your computer and use it in GitHub Desktop.
Save davestevens/9782498 to your computer and use it in GitHub Desktop.
JS For Loops?
// 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