querySelector id vs class vs element vs attribute version 2

JavaScript performance comparison

Revision 72 of this test case created by

Preparation code

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
var i, $p = $('p');
for (i = 0; i < 500; i++)
$('<span></span>').attr("id", i).attr("class", i).attr("data-attribute", i).appendTo($p);

function getElementsByAttribute(attr) {
  var allElements  = Array.prototype.slice.call(document.getElementsByTagName("*"));
  var elementCount = allElements.length;
  for (var i = 0; i < elementCount; i++) {
    if (!allElements[i].hasAttribute(attr)) {
      allElements.splice(i,1);
      elementCount--;
      i--;
    }
  }
  return allElements;
} 
</script>
<div>
  <p>
    <span id="id" class="class" data-attribute="attribute">
      Content
    </span>
  </p>
</div>
    

Preparation code output

<div> <p> <span id="id" class="class" data-attribute="attribute"> Content </span> </p> </div>

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
getElementsByAttribute
getElementsByAttribute("data-attribute");
pending…
querySelector attribute
document.querySelector("[data-attribute='attribute']");
pending…
querySelector element / attribute
document.querySelector("span[data-attribute='attribute']");
pending…
querySelector class / attribute
document.querySelector(".class[data-attribute='attribute']");
pending…
querySelector element / class / attribute
document.querySelector("span.class[data-attribute='attribute']");
pending…
querySelector attribute name
document.querySelector("[data-attribute]");
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

Content