Find out if a sorted array of integers contains a number

Benchmark created on


Setup

const NR_ELEMENTS = 1000000;
const NR_CHECK = 1000;

function fillArray(nrElements) {
  let nrs = [];
  let cnt = 0;
  let cur = 0;

  while (cnt < nrElements) {
    if (Math.random() > 0.2) {
      nrs.push(cur);
      cnt++;
    }
    cur++;
  }
  return nrs;
}

const arr = fillArray(NR_ELEMENTS);

const indexedArray = new Array(arr[arr.length - 1]);
indexedArray.fill(false);

for (let i = 0, l = arr.length; i < l; i++) {
	indexedArray[arr[i]] = true;
}

const set = new Set();
for (let i = 0, l = arr.length; i < l; i++) {
	set.add(arr[i]);
}

const arrayToCheck = fillArray(NR_CHECK);

Test runner

Ready to run.

Testing in
TestOps/sec
IndexedArray without count
for (let i = 0, l = arrayToCheck.length; i < l; i++) {
	let has = indexedArray[arrayToCheck[i]];
}
ready
Set without count
for (let i = 0, l = arrayToCheck.length; i < l; i++) {
	let has = set.has(arrayToCheck[i]);
}
ready
IndexedArray with count
let found = 0;
for (let i = 0, l = arrayToCheck.length; i < l; i++) {
	let has = indexedArray[arrayToCheck[i]];
	if (has) found++;
}
ready
Set with count
let found = 0;
for (let i = 0, l = arrayToCheck.length; i < l; i++) {
	let has = set.has(arrayToCheck[i]);
	if (has) found++;
}
ready

Revisions

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