RegExp vs querySelectorAll

JavaScript performance comparison

Revision 3 of this test case created by fkm

Info

I want to see if my function is worth anything.

Preparation code

<span>This</span>
<span class="test">is</span>
<span>a</span>
<span id="test">Test</span>
<span>!</span>
<script>
Benchmark.prototype.setup = function() {
    var regex_id = /#-?([_a-z]|[\x200-\x377]|(\\[0-9a-f]{1,6}(\r\n|[ \t\r\n\f])?|\\[^\r\n\f0-9a-f]))([_a-z0-9-]|[\x200-\x377]|(\\[0-9a-f]{1,6}(\r\n|[ \t\r\n\f])?|\\[^\r\n\f0-9a-f]))*/i,
      regex_class = /\.-?([_a-z]|[\x200-\x377]|(\\[0-9a-f]{1,6}(\r\n|[ \t\r\n\f])?|\\[^\r\n\f0-9a-f]))([_a-z0-9-]|[\x200-\x377]|(\\[0-9a-f]{1,6}(\r\n|[ \t\r\n\f])?|\\[^\r\n\f0-9a-f]))*/i,
      regex_tag = /(-?([_a-z]|[\x200-\x377]|(\\[0-9a-f]{1,6}(\r\n|[ \t\r\n\f])?|\\[^\r\n\f0-9a-f]))([_a-z0-9-]|[\x200-\x377]|(\\[0-9a-f]{1,6}(\r\n|[ \t\r\n\f])?|\\[^\r\n\f0-9a-f]))*|\*)/i;
   
    function versionA(selector) {
      var result;
   
      if (regex_id.test(selector)) {
        result = document.getElementById(selector.substring(1));
      } else if (regex_class.test(selector)) {
        result = document.getElementsByClassName(selector.substring(1));
      } else if (regex_tag.test(selector)) {
        result = document.getElementsByTagName(selector);
      } else {
        result = document.querySelectorAll(selector);
      }
   
      return result;
    };
   
    function versionB(selector) {
      return document.querySelectorAll(selector);
    };
};
</script>

Preparation code output

This is a Test !

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, Tag
versionA('span');
pending…
querySelectorAll, Tag
versionB('span');
pending…
RegExp, ID
versionA('#test');
pending…
querySelectorAll, ID
versionB('#test');
pending…
RegExp, Class
versionA('.test');
pending…
querySelectorAll, Class
versionB('.test');
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

fkm commented :

Sources

  • http://stackoverflow.com/a/2812097
  • http://www.w3.org/TR/CSS21/grammar.html#scanner

Further Reading

  • http://developer.mozilla.org/docs/Web/API/document.getElementById
  • http://developer.mozilla.org/docs/Web/API/document.getElementsByClassName
  • http://developer.mozilla.org/docs/Web/API/document.getElementsByTagName
  • http://developer.mozilla.org/docs/Web/API/Document.querySelectorAll

Add a comment