convert HTML collection into array

JavaScript performance comparison

Revision 8 of this test case created

Info

Some of the previous revisions were incrementing the amount of children in parentdiv after each loop, resulting in slower code the longer the benchmark ran.

This revision does not have that issue.

The previous revision of this also had some embarrassing typos that this version has fixed.

Preparation code

<div id="parent">
</div>
<script>
var parentNode = document.getElementById('parent'), i, objs;
for (length = 1000, i = length; i >= 0; i--) {
  parentNode.appendChild(document.createElement('div'));
}
objs = parentNode.getElementsByTagName('div');
</script>

Preparation code output

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
HTML collection
var collection = objs, _len = collection.length, obj;
for (var i = 0; i < _len; i++) {
  obj = collection[i];
}
pending…
convert HTML collection into Array
var collection = objs, _len = collection.length, objsArray = [], i = 0, obj;
for (objsArray.length = _len; i < _len; i++) {
  objsArray[i] = collection[i];
}
for (i = 0, _len = objsArray.length; i < _len; i++) {
  obj = objsArray[i];
}
pending…
convert HTML collection into Array with Array.slice
var objsArray = Array.prototype.slice.call(objs), _len = objsArray.length, i, obj;
for (i = 0; i < _len; i++) {
  obj = objsArray[i];
}
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:

1 comment

Anonymous commented :

I think the biggest problem with this benchmark is that it doesn't measure the performance of anything actually being done with said elements after they're collected, other than assigning them. I feel that any performance gains on further tasks will still be greater once converting to an array (which "convert HTML collection into Array" does fastest.)

Add a comment