iterating objects

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();
}

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

Revisions

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