Iterating over all object entries. for vs for-in vs for-of (v2)

Revision 2 of this benchmark created on


Description

Case of a small object, 7 keys

Setup

const obj = {
	a: 0,
	b: 2, 
	c: 3,
	d: 4,
	e: 5,
	f: 6,
	g: 7,
};

let counter = 0; // dummy counter that adds minimal overhead but prevents theoretically possible runtime optimization

Teardown

counter = 0;

Test runner

Ready to run.

Testing in
TestOps/sec
for
const entries = Object.entries(obj);
const len = entries.length; 

for (let i = 0; i < len; i++) {
	if (entries[i][1]) {
		counter++;
	}
}

if (counter !== 6) console.log('err');
ready
for-in
for (let key in obj) {
	if (obj[key]) {
		counter++;
	}
}

if (counter !== 6) console.log('err');
ready
for-of
const entries = Object.entries(obj);

for (let [key, value] of entries) {
	if (value) {
		counter++;
	}
}

if (counter !== 6) console.log('err');
ready
for 2
const keys = Object.keys(obj);
const len = keys.length; 

for (let i = 0; i < len; i++) {
	if (obj[keys[i]]) {
		counter++;
	}
}

if (counter !== 6) console.log('err');
ready

Revisions

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