regexp vs indexOf

JavaScript performance comparison

Revision 7 of this test case created

Info

Checking the performance cost of using a regexp instead of String#indexOf.

Preparation code

<div id="foo" class="a foo bar"></div>
<script>
Benchmark.prototype.setup = function() {
    var r;
    var element = document.getElementById('foo');
    var reContains = /foo/;
    var strContains = 'foo';
   
    function dynamicRegExp(node) {
      return RegExp('foo').test(node.className);
    }
   
    function inlineRegExp(node) {
      return /foo/.test(node.className);
    }
   
    function storedRegExp(node) {
      return reContains.test(node.className);
    }
   
    function stringIndexOf(node) {
      return node.className.indexOf('foo') > -1;
    }
   
    function storedStringIndexOf(node) {
      return node.className.indexOf(strContains) > -1;
    }
   
};
</script>

Preparation code output

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
dynamic regexp
r = dynamicRegExp(element);
pending…
inline regexp
r = inlineRegExp(element);
pending…
stored regexp
r = storedRegExp(element);
pending…
string indexOf
r = stringIndexOf(element);
pending…
stored string indexOf
r = storedStringIndexOf(element);
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

1 comment

John-David Dalton commented :

The point of this test is to show that you should avoid making blanket assumptions about performance and that you shouldn't fear the RegExp :)

I wanted to use a common use case of checking if an element has a specific class name because I've seen libs toss-n-turn over using one or the other.

This revision is less representative of the use case as now it will match className values like 'foobar' instead of just 'foo'.

Comment form temporarily disabled.

Add a comment