non-vanilla getElementById

JavaScript performance comparison

Revision 33 of this test case created by AjiTae

Preparation code

<p id="foo">Foo</p>
<p id="bar">Bar</p>
<p id="baz">Baz</p>
      
<script>
Benchmark.prototype.setup = function() {
  var idSelectorRegexp = /^#[a-zA-Z]+[a-zA-Z0-9_\-]*$/;
  
  var withSlice = function(query){
    // pure ID selector?
    if (idSelectorRegexp.test(query))
      return document.getElementById(query.slice(1));
    else
      return document.querySelector(query);
  };
  var withSubstring = function(query){
    // pure ID selector?
    if (idSelectorRegexp.test(query))
      return document.getElementById(query.substring(1));
    else
      return document.querySelector(query);
  };
  var withSubstr = function(query){
    // pure ID selector?
    if (idSelectorRegexp.test(query))
      return document.getElementById(query.substr(1));
    else
      return document.querySelector(query);
  };
  
  var withBind = function(query){};
  withBind.id = document.getElementById.bind(document);
  
  var withReturn = function(query){};
  withReturn.id = function(id){ return document.getElementById(id)}

};
</script>

Preparation code output

<p id="foo">Foo</p> <p id="bar">Bar</p> <p id="baz">Baz</p>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
getElementById
var bar = document.getElementById("bar");
var baz = document.getElementById("baz");
var foo = document.getElementById("foo");
pending…
querySelector
var bar = document.querySelector("#bar");
var baz = document.querySelector("#baz");
var foo = document.querySelector("#foo");
pending…
withSlice
var bar = withSlice("#bar");
var baz = withSlice("#baz");
var foo = withSlice("#foo");
pending…
withSubstring
var bar = withSubstring("#bar");
var baz = withSubstring("#baz");
var foo = withSubstring("#foo");
pending…
withSubstr
var bar = withSubstr("#bar");
var baz = withSubstr("#baz");
var foo = withSubstr("#foo");
pending…
return getElementById
var bar = withReturn.id("bar");
var baz = withReturn.id("baz");
var foo = withReturn.id("foo");
pending…
bind getElementById
var bar = withBind.id("bar");
var baz = withBind.id("baz");
var foo = withBind.id("foo");
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.

0 Comments

Foo

Bar

Baz