What has higher performance used within large loops: .indexOf(str) or .match(regex)?

arrays, indexof, javascript, match, regex

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.

Problem

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; } ```

Original source