Test Search by string

Benchmark created on


Setup

const sanitizeSearchTerms = (query) => {
    return query.replace(/[^a-zA-Z0-9 ]/g, '');
}

const ALL_TERMS = (query) => {
  const terms = sanitizeSearchTerms(query).split(' ');
  return new RegExp(`(?=.*${terms.join(')(?=.*')})`, 'i');
}

const generateSampleData = (size) => {
    const data = [];
    for (let i = 0; i < size; i++) {
        data.push(`${Math.random().toString(36).substring(2, 15)}${Math.random().toString(36).substring(2, 15)}`);
    }
    return data;
};

// Approach using Regular Expression
const benchmarkRegex = (items, query) => {
  const start = performance.now();
  const filteredItems = items.filter((i) => i.match(ALL_TERMS(query)));
  const end = performance.now();
  console.log(`Regular Expression: ${end - start} milliseconds`);
};

// Approach using indexOf
const benchmarkIndexOf = (items, query) => {
  const start = performance.now();
  const queryWords = query.toLowerCase().split(' ');
  const filteredItems = items.filter((item) => {
    // Check if all words in the query are present in the item
    return queryWords.every((word) => item.includes(word));
  });
  const end = performance.now();
  console.log(`IndexOf Method: ${end - start} milliseconds`);
};

// Approach using indexOf
const benchmarkIncludes = (items, query) => {
    const start = performance.now();
    const queryWords = query.toLowerCase().split(' ');
    const filteredItems = items.filter((item) => {
        // Check if all words in the query are present in the item
        return queryWords.every((word) => item.includes(word));
      });
    const end = performance.now();
    console.log(`Includes Method: ${end - start} milliseconds`);
  };

Test runner

Ready to run.

Testing in
TestOps/sec
Test Regex
const smallItems = generateSampleData(100);
const mediumItems = generateSampleData(2000);
const largeItems = generateSampleData(20000);
const query = '12 321';

for (let i = 0; i < 10; i++) {
    benchmarkRegex(smallItems, query);
    benchmarkRegex(mediumItems, query);
    benchmarkRegex(largeItems, query);
  }
ready
Test Includes
const smallItems = generateSampleData(100);
const mediumItems = generateSampleData(2000);
const largeItems = generateSampleData(20000);
const query = '12 321';

for (let i = 0; i < 10; i++) {
    benchmarkIncludes(smallItems, query);
    benchmarkIncludes(mediumItems, query);
    benchmarkIncludes(largeItems, query);
  }
ready
Test IndexOf
const smallItems = generateSampleData(100);
const mediumItems = generateSampleData(2000);
const largeItems = generateSampleData(20000);
const query = '12 321';

for (let i = 0; i < 10; i++) {
    benchmarkIndexOf(smallItems, query);
    benchmarkIndexOf(mediumItems, query);
    benchmarkIndexOf(largeItems, query);
  }
ready

Revisions

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