views:

366

answers:

3

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;
     }
A: 

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.

John Fisher
+8  A: 

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.

newacct
+1 I cannot imagine how a regular expression could beat indexOf. If you don't need regex-power, don't use regex.
Michael Haren
A: 

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.

kennebec