regexp vs indexOf (v14)

Revision 14 of this benchmark created by Gmice on


Description

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

Setup

var r;
    var reContains = /(?:^| )foo(?: |$)/;
    
    function dynamicRegExp(className) {
      return RegExp('(?:^| )foo(?: |$)').test(className);
    }
    
    function inlineRegExp(className) {
      return /(?:^| )foo(?: |$)/.test(className);
    }
    
    function storedRegExp(className) {
      return reContains.test(className);
    }
    
    function stringIndexOf(className) {
      return (' ' + className + ' ').indexOf(' foo ') > -1;
    }
    
    function stringIndexOf2(className) {
      var i = className.indexOf('foo');
      return (i != -1) && (i == 0 || className.charAt(i - 1) == ' ') && (i == className.length - 3 || className.charAt(i + 3) == ' ');
    }

Test runner

Ready to run.

Testing in
TestOps/sec
dynamic regexp
r = dynamicRegExp('a foo bar');
ready
inline regexp
r = inlineRegExp('a foo bar');
ready
stored regexp
r = storedRegExp('a foo bar');
ready
string indexOf
r = stringIndexOf('a foo bar');
ready
string indexOf 2
r = stringIndexOf2('a foo bar');
ready

Revisions

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