What has higher performance used within large loops: .indexOf(str) or .match(regex)?
-
06-07-2019 - |
Question
I have this array.prototype on my page and it seems to be sucking up a lot of processing time:
Array.prototype.findInArray = function(searchStr) {
var returnArray = false;
for (i=0; i<this.length; i++) {
if (typeof(searchStr) == 'function') {
if (searchStr.test(this[i])) {
if (!returnArray) { returnArray = [] }
returnArray.push(i);
}
} else {
var regexp = new RegExp(".*" + searchStr + ".*");
if (this[i].match(regexp)) {
if (!returnArray) { returnArray = [] }
returnArray.push(i);
}
}
}
return returnArray;
}
Solution
First of all, you know that you don't have to have the ".*" on either side, right? A regular expression already by default will match anywhere inside the string. Second, if you are just searching for a constant string, and don't need to use any of the advanced stuff that regular expressions offer, then it's definitely faster to use .indexOf()
. Plus that way you won't have to worry about escaping characters that have special meaning.
OTHER TIPS
Regular expressions can vary wildly. I imagine that a simple, well-crafted regular expression might work as fast or faster than indexOf(). On the other hand, a complex regular expression would need more time since it's doing more work.
You also have a browser implementation issue clouding matters. Short of writing a timed loop to measure the time taken for each browser to do each type of detection with your specific needs, you can't really get a solid answer.
What is worse is you create a new regular expression object on every iteration of the loop- define it once, outside the loop, or pass it as an argument.
Also, for this use, test is better and quicker than match.