RegExp vs querySelectorAll

JavaScript performance comparison

Revision 4 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][a-z0-9]+$/i,
      regex_class = /^\.[a-z][a-z0-9]+$/i,
      regex_tag = /^[a-z]+$/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:

0 comments

Add a comment