Form Traversal Test Speed (v4)

Revision 4 of this benchmark created on


Description

Testing traversal speed of HTMLFormElement.elements vs. other methods.

Speeds of QSA (QSA + jQuery) results are misleading unless queries are dynamically switched between iterations as in many cases (Opera 11 especially), the queries get cached.

Preparation HTML

<form method="post" action="./" id="foo">
  <input type="checkbox" name="bar" value="1" checked />
  <input type="checkbox" name="bar" value="2" checked />
  <input type="checkbox" name="bar" value="3" />
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>
<script>
  var foo = document.getElementById("foo"),
      numChecked = 0;
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
HTMLFormElement.elements
var i = 0;
var node;
var bar = "lasjkfjkasdfhksgdfasdhkflasflsdfldf";
var cached;
bar = bar.slice(0, Math.floor(Math.random() * bar.length));
foo = document.getElementsByTagName("form")[0];
foo.id = bar;
cached = [].slice.call(foo.elements);
if(Array.prototype.forEach)
{
        cached.forEach(function(el, i, array)
        {
                if(el.tagName === "INPUT" && el.type === "checkbox")
                {
                        if(el.checked)
                        {
                                numChecked++;
                        }
                }
        });
}else
{
        for(i;i<foo.elements.length;i++)
        {
            node = foo.elements[i];
            if(node.tagName === "INPUT" && node.type === "checkbox")
            {
                if(node.checked)
                {
                    numChecked++;
                }  
            }
            node = null;
        }
}
ready
QuerySelectorAll
var bar = "lasjkfjkasdfhksgdfasdhkflasflsdfldf";
bar = bar.slice(0, Math.floor(Math.random() * bar.length));
foo = document.getElementsByTagName("form")[0];
foo.id = bar;
numChecked = foo.querySelectorAll("input[type=checkbox]:checked").length;
ready
jQuery Attribute Query
var bar = "lasjkfjkasdfhksgdfasdhkflasflsdfldf";
bar = bar.slice(0, Math.floor(Math.random() * bar.length));
foo = document.getElementsByTagName("form")[0];
foo.id = bar;
numChecked = $(foo).find("input[type=checkbox]:checked").get().length;
ready

Revisions

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