Object.values vs iterator (v3)

Revision 3 of this benchmark created on


Setup

const SIZE = 10;
const obj = {};
for (let i = 0; i < SIZE; i++) {
  obj["key" + i] = i;
}

// Generator version
function* values(obj) {
  for (const key in obj) {
    if (obj.hasOwnProperty(key)) {
      yield obj[key];
    }
  }
}

function altForEach(obj, cb) {
  for (const key in obj) {
  	if (obj.hasOwnProperty(key)) {
  	  cb(key);
  	}
  }
}

// Predefine a dummy function to avoid in-test overhead
function noop(x) {}

Test runner

Ready to run.

Testing in
TestOps/sec
Object.values()
for (const v of Object.values(obj)) {
  noop(v);
}
ready
Generator-based iterator
for (const v of values(obj)) {
  noop(v);
}
ready
Classic for…in loop
for (const key in obj) {
	if (!obj.hasOwnProperty(key)) continue;
    noop(obj[key]);
}
ready
Cached keys array
const keys = Object.keys(obj);
for (let i = 0; i < keys.length; i++) {
  noop(obj[keys[i]]);
}
ready
Alternative forEach
altForEach(obj, (key) => {
	noop(obj[key])
});
ready
hasOwn for..each
for (const key in obj) {
	if (!Object.hasOwn(obj, key)) continue;
    noop(obj[key]);
}
ready

Revisions

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