object.keys vs for-in (v8)

Revision 8 of this benchmark created on


Setup

const ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

function randomString(length) {
  const out = [];
  for (let i = 0; i < length; i++) {
    const randomChar = ALPHABET[Math.floor(Math.random() * ALPHABET.length)];
    out.push(randomChar);
  }
  return out.join("");
}

function randomObject(size) {
  const out = {};
  for (let i = 0; i < size; i++) {
  	out[randomString(10)] = Math.random();
  }
  return out;
}

function current(data) {
  console.log(Object.keys(data).length === 0);
}

function suggested(data) {
  for (const key in data) {
    if (Object.hasOwn(data, key)) {
      console.log(false);
      return;
    }
  }
  console.log(true);
  return;
}

const data = randomObject(100_000);

Test runner

Ready to run.

Testing in
TestOps/sec
object.keys
current(data);
ready
for-in
suggested(data);
ready

Revisions

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