Fast array search

Benchmark created on


Setup

function generatePoints(count = 10000, min = 0, max = 300) {
    const points = new Array(count);
    const range = max - min + 1;

    for (let i = 0; i < count; i++) {
        points[i] = {
            x: Math.floor(Math.random() * range) + min,
            y: Math.floor(Math.random() * range) + min
        };
    }

    return points;
}

function buildPointIndex(points, keyCreator) {
    const index = new Set();
    for (const p of points) {
        index.add(keyCreator(p));
    }
    return index;
}

function toIndexedArray(array, keyCreator) {
  let result = {
    index: new Set(),
    keyCreator,
    check(value) {
      return this.index.has(this.keyCreator(value))
    }
  };

  for (const arrayItem of array) {
      result.index.add(keyCreator(arrayItem));
  }

  return result;
}

var mainArr = generatePoints();
var mainSet = toIndexedArray(mainArr, (p) => p.x + "," + p.y);

var mainSet2 = toIndexedArray(mainArr, (p) => p.x + p.y*1000);

var mainSet3 = toIndexedArray(mainArr, (p) => (p.x | (p.y << 10)));

var mainSet4 = toIndexedArray(mainArr, (p) => ((p.y << 16) | p.x) >>> 0);

var arrToCheck = generatePoints();

Test runner

Ready to run.

Testing in
TestOps/sec
Array.Find
for (const check of arrToCheck) {
	let r = mainArr.find(p => p.x == check.x && p.y == check.y) != undefined;
}
ready
Set.has string key
for (const check of arrToCheck) {
	let r = mainSet.check(check);
}
ready
Set.has intkey
for (const check of arrToCheck) {
	let r = mainSet2.check(check);
}
ready
Set.has binary shift key
for (const check of arrToCheck) {
	let r = mainSet3.check(check);
}

ready
Set.has Uint32 key
for (const check of arrToCheck) {
	let r = mainSet4.check(check);
}
ready

Revisions

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