getElementsByClassName and filtering vs. document.evaluate and XPathExpression.evaluate (v2)

Revision 2 of this benchmark created by Sergey Kolosov on


Preparation HTML

<ul>
  <li><a href="#" class="foo">Item</a></li>
  <li><a href="#" class="foo" data-bar="true">Item</a></li>
  <li><a href="#" class="foo">Item</a></li>
  <li><a href="#" class="foo" data-bar="true">Item</a></li>
  <li><a href="#" class="foo">Item</a></li>
</ul>
<script>
  var list, len, i, result;
  
  var filter = Array.filter || Benchmark.filter;
  
  function notBar(el) {
   return !el.hasAttribute('data-bar');
  }
  
  var snapshotType = 6; /* XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE */
  
  var fooAndNotBarQuery = "//*[contains(concat(' ', @class, ' '), ' foo ') and not (@data-bar)]";
  var expression = document.createExpression(fooAndNotBarQuery, null);
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
Using getElementsByClassName and filtering
list = document.getElementsByClassName("foo");
list = filter(list, notBar);
len = list.length;

for (i = 0; i < len; i++) {
 result = list[i];
}
ready
Using document.evaluate
list = document.evaluate(fooAndNotBarQuery, document, null, snapshotType, null);
len = list.snapshotLength;

for (i = 0; i < len; i++) {
 result = list.snapshotItem(i);
}
ready
Using XPathExpression.evaluate (reuse expression)
list = expression.evaluate(document, snapshotType, null);
len = list.snapshotLength;

for (i = 0; i < len; i++) {
 result = list.snapshotItem(i);
}
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.

  • Revision 2: published by Sergey Kolosov on