regexp vs indexOf

JavaScript performance comparison

Revision 10 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 cacheRegexp = {};
    function cachedRegExp(node, _class) {
      return (cacheRegexp[_class] || (cacheRegexp[_class] = RegExp('(?:^| )'+ _class +'(?: |$)'))).test(node.className);
    }
   
    var cacheClassName = {};
    function cachedIndexOf(node, _class) {
      var className = node.className;
      return (cacheClassName[className] || (cacheClassName[className] = ' '+ className +' ')).indexOf(cacheClassName[_class] || (cacheClassName[_class] = ' '+ _class +' ')) > -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
regexp
r = cachedRegExp(element, 'foo');
pending…
indexOf
r = cachedIndexOf(element, 'foo');
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:

0 comments

Add a comment