regexp vs indexOf

JavaScript performance comparison

Revision 7 of this test case created


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

Preparation code

<div id="foo" class="a foo bar"></div>
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;

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);
inline regexp
r = inlineRegExp(element);
stored regexp
r = storedRegExp(element);
string indexOf
r = stringIndexOf(element);
stored string indexOf
r = storedStringIndexOf(element);

Compare results of other browsers


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