js string search performance

Benchmark created on


Setup

const SIZE = 1000000; // Define the size of the dataset
const SEARCH_VALUE = "target_value";

// Generate test data
const array = Array.from({ length: SIZE }, (_, i) => "value_" + i);
array[SIZE - 1] = SEARCH_VALUE; // Ensure the value is in the array

const VALUES_TO_SEARCH = [SEARCH_VALUE, 'value_100000', 'value_34234', 'foo', 'bar']

let object = {};
for (const value of array) {
    object[value] = true;
}

let set = new Set(array);

let map = new Map();
for (const value of array) {
    map.set(value, true);
}

Test runner

Ready to run.

Testing in
TestOps/sec
array
    console.time("Array search");
    VALUES_TO_SEARCH.forEach(value => {
      array.includes(value);
    })
    console.timeEnd("Array search");
ready
map (has)
    console.time("Map search");
    VALUES_TO_SEARCH.forEach(value => {
      map.has(value);
    })
    console.timeEnd("Map search");
ready
set
    console.time("Set search");
    VALUES_TO_SEARCH.forEach(value => {
      set.has(value);
    })
    console.timeEnd("Set search");
ready
object
    console.time("Object search");
    VALUES_TO_SEARCH.forEach(value => {
      object[value];
    })
    console.timeEnd("Object search");
ready
map (get)
    console.time("Map search");
    VALUES_TO_SEARCH.forEach(value => {
      map.get(value);
    })
    console.timeEnd("Map search");
ready
map (get + cast to boolean)
    console.time("Map search");
    VALUES_TO_SEARCH.forEach(value => {
      !!map.get(value);
    })
    console.timeEnd("Map search");
ready
object (has own property)
    console.time("Object search");
    VALUES_TO_SEARCH.forEach(value => {
      Object.prototype.hasOwnProperty.call(object, value);
    })
    console.timeEnd("Object search");
ready

Revisions

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