iterating objects (v2)

Revision 2 of this benchmark created on


Setup

const data = {};
const chars = "abcdefghijklmnopqrstuvwxyz";

for (let i = 0; i < 1000; i++) {
	let name;

	do {
		name = "";
		for (let j = 0; j < 32; j++) {
			name += chars[Math.floor(Math.random() * 26)];
		}
	} while (data[name] != null);

	data[name] = Math.random();
}

if (Object.keys(data).length !== 1000) throw new TypeError( "bad setup" );

Test runner

Ready to run.

Testing in
TestOps/sec
for-in loop
let sum = 0;
for (const name in data) {
	if (data.hasOwnProperty(name)) {
		sum += data[name];
	}
}
ready
for-of loop on keys
let sum = 0;
for (const name of Object.keys(data)) {
	sum += data[name];
}
ready
for-of loop on values
let sum = 0;
for (const value of Object.values(data)) {
	sum += value;
}
ready
for-of loop on entries
let sum = 0;
for (const [, value] of Object.entries(data)) {
	sum += value;
}
ready
reduce on keys w/ arrow function
const sum = Object.keys(data).reduce((s, name) => s + data[name], 0);
ready
reduce on values w/ arrow function
const sum = Object.values(data).reduce((s, v) => s + v, 0);
ready
legacy for loop on keys
const keys = Object.keys(data);
let sum = 0;

for ( let i = 0; i < keys.length; i++ ) {
	sum += data[keys[i]];
}
ready
legacy for loop on values
const values = Object.values(data);
let sum = 0;

for ( let i = 0; i < values.length; i++ ) {
	sum += values[i];
}
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.