object.keys vs for-in (v5)

Revision 5 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;
}

Test runner

Ready to run.

Testing in
TestOps/sec
object.keys
function current(data) {
  return Object.keys(data).length === 0;
}

current(randomObject(10_000));
ready
for-in
function suggested(data) {
  for (const key in data) {
    if (Object.hasOwn(data, key)) {
      return false;
    }
  }
  return true;
}

suggested(randomObject(10_000));
ready
object.values
function alt1(data) {
  return Object.values(data).length === 0;
}

alt1(randomObject(10_000));
ready
object.entries
function alt2(data) {
  return Object.entries(data).length === 0;
}

alt2(randomObject(10_000));
ready

Revisions

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