Compare performance between indexOf and regex
function searchUsingIndexOf(text, searchTerm) {
return text.toLowerCase().indexOf(searchTerm.toLowerCase()) !== -1;
}
function searchUsingRegex(text, searchTerm) {
const regex = new RegExp(searchTerm, 'i');
// return regex.test(text);
return text.match(regex) ? true : false;
}
// Test data
const text = 'There are hundreds of books';
const searchTerm1 = 'hundreds of';
// const searchTerm2 = `"text":"[^"]*${searchTerm1}[^"]*"`;
const searchTerm2 = `${searchTerm1}`;
// Measure performance for searchUsingRegex
const startRegex = performance.now();
const resultRegex = searchUsingRegex(text, searchTerm2);
const endRegex = performance.now();
const timeElapsedRegex = endRegex - startRegex;
// Measure performance for searchUsingIndexOf
const startIndexOf = performance.now();
const resultIndexOf = searchUsingIndexOf(text, searchTerm1);
const endIndexOf = performance.now();
const timeElapsedIndexOf = endIndexOf - startIndexOf;
console.log('Search using indexOf:');
console.log('Result: ', resultIndexOf);
console.log('Time elapsed (milliseconds): ', timeElapsedIndexOf);
console.log('Search using regex:');
console.log('Result: ', resultRegex);
console.log('Time elapsed (milliseconds): ', timeElapsedRegex);