Skip to content

Instantly share code, notes, and snippets.

@chjj chjj/loop-bench.js
Created May 1, 2011

Embed
What would you like to do?
loop benchmarks
var a = [];
for (var i = 0; i < 100000; i++) a.push('a');
var o = {};
for (var i = 0; i < 100000; i++) o['key_' + i] = 'a';
(function() {
var s = Date.now();
var i = a.length;
while (i--) {
var b = a[i];
}
console.log('while array:', Date.now() - s);
})();
(function() {
var s = Date.now();
var k = Object.keys(o), i = k.length;
while (i--) {
var b = o[k[i]];
}
console.log('while object:', Date.now() - s);
})();
(function() {
var s = Date.now();
var i = a.length - 1;
do {
var b = a[i];
} while (i--);
console.log('do-while array:', Date.now() - s);
})();
(function() {
var s = Date.now();
var k = Object.keys(o), i = k.length-1;
do {
var b = o[k[i]];
} while (i--);
console.log('do-while object:', Date.now() - s);
})();
(function() {
var s = Date.now();
for (var i = 0, l = a.length; i < l; i++) {
var b = a[i];
}
console.log('for array:', Date.now() - s);
})();
(function() {
var s = Date.now();
var k = Object.keys(o);
for (var i = 0, l = k.length; i < l; i++) {
var b = o[k[i]];
}
console.log('for object:', Date.now() - s);
})();
(function() {
var s = Date.now();
a.forEach(function(v) {
var b = v;
});
console.log('forEach array:', Date.now() - s);
})();
(function() {
var s = Date.now();
Object.keys(o).forEach(function(k) {
var b = o[k];
});
console.log('forEach object:', Date.now() - s);
})();
(function() {
var s = Date.now();
for (var k in o) {
var b = o[k];
};
console.log('for...in object:', Date.now() - s);
})();
(function() {
var s = Date.now();
for (var k in o) {
if (o.hasOwnProperty(k)) var b = o[k];
};
console.log('for...in wrapper object:', Date.now() - s);
})();
(function() {
var s = Date.now();
for (var k in a) {
var b = a[k];
};
console.log('for...in array:', Date.now() - s);
})();
(function() {
var s = Date.now();
for (var k in a) {
if (a.hasOwnProperty(k)) var b = a[k];
};
console.log('for...in wrapper array:', Date.now() - s);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.