Array vs Set vs Object contains

JavaScript performance comparison

Test case created by gavar

Preparation code

<script>
  // use developer tools to adjust N
  let N = 100; debugger; 
  console.log("N:", N);

  const keys = Array.from(Array(N).keys());
  const set = new Set(keys);
  const array = Array.from(keys).sort(shuffler);
  const object = Object.assign({}, keys.map(Number.isInteger));

  function shuffler() {
    return Math.random() - 0.5;
  }

  function validate(v) {
    console.assert(v === N, "expected %s but was %s", N, v);
  }
</script>

    

Preparation code output

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
array.includes
let counter = 0;
for (const key of keys)
  if (array.includes(key))
    counter++;

validate(counter);
pending…
set.has
let counter = 0;
for (const key of keys)
  if (set.has(key))
    counter++;

validate(counter);
pending…
object.hasOwnProperty
let counter = 0;
for (const key of keys)
  if (object.hasOwnProperty(key))
    counter++;

validate(counter);
pending…
key in object
let counter = 0;
for (const key of keys)
  if (key in object)
    counter++;

validate(counter);
pending…
object[key]
let counter = 0;
for (const key of keys)
  if (object[key])
    counter++;

validate(counter);
pending…
array.indexOf
let counter = 0;
for (const key of keys)
  if (array.indexOf(key) + 1)
    counter++;

validate(counter);
pending…
array.find
let counter = 0;
for (const key of keys)
  if (array.find(x => x === key))
    counter++;

validate(counter);
pending…

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

Compare results of other browsers

0 Comments