regexp vs indexOf (v30)

Revision 30 of this benchmark created on


Description

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

Preparation HTML

<div id="foo" class="a foo bar"></div>

Setup

var r;
    var element = document.getElementById('foo');
    var reContains = /(?:^| )foo(?: |$)/;
    const reContainsConst = RegExp(' /(?:^| )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 constRegExp(node) {
      return reContainsConst.test(node.className);
    }
    
    function stringIndexOf(node) {
      return (' ' + node.className + ' ').indexOf(' foo ') > -1;
    }

Test runner

Ready to run.

Testing in
TestOps/sec
dynamic regexp
r = dynamicRegExp(element);
ready
inline regexp
r = inlineRegExp(element);
ready
stored regexp
r = storedRegExp(element);
ready
string indexOf
r = stringIndexOf(element);
ready
const regex
r = constRegExp(element);
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.