I'm trying to implement a search of an object with multiple key/value pairs that can be either string
or number
.
This is what I'm currently using (simplified, of course):
const input = 'Hello WORld 21'; // this could also be of type number
const search = 'O w'; // this could also be of type number
let result = true;
let startTime, endTime;
const t0 = performance.now();
for (let i = 0; i < 1000000; i++) {
let parsedInput = JSON.stringify(input).toLowerCase().replace(/(^"|"$)/g, '');
let parsedSearch = JSON.stringify(search).toLowerCase().replace(/(^"|"$)/g, '');
result = parsedInput.indexOf(parsedSearch);
}
const t1 = performance.now();
console.log(`Call to doSomething took ${t1 - t0} milliseconds with result = ${result}`);
// ~393ms on a Ryzen 5600X
So this works, but seems to be expensive, especially when I go through tens of thousands of objects (or even more). So I wonder if there is a more elegant way to implement a search like this.
Thank you in advance!
Edit: Based on Sergio J's answer, here is what I got now:
const t2 = performance.now();
let i, s;
for (let j = 0; j < 1000000; j++) {
i = isNaN(input) ? input.toLowerCase() : input.toString().toLowerCase();
s = isNaN(search) ? search.toLowerCase() : search.toString().toLowerCase();
result = i.indexOf(s);
}
const t3 = performance.now();
console.log(`Call to doSomething took ${t3 - t2} milliseconds with result = ${result}`);
// ~66ms on a Ryzen 5600X