For loop effectivity (v2)

Revision 2 of this benchmark created by Jakub Mareda on


Description

I'm testing whether it's faster to use the Array.length and HTMLColection.length or it's better to save them in variables and look in the variables.

Setup

var elm_array = document.getElementsByTagName("*");
    var selectBox = document.createElement("select");
    var array2 = [];
    var short_array = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24];
    
    for(var i=0,l=elm_array.length;i<l; i++) {
      array2.push(Math.random());
      selectBox.appendChild(document.createElement("option"));
    }

Test runner

Ready to run.

Testing in
TestOps/sec
Normal for loop (array)
for(var i=0; i<array2.length; i++);
 
ready
For loop with length in variable (array)
for(var i=0, l=array2.length; i<l; i++);
ready
Normal for loop (HTMLCollection)
for(var i=0; i<elm_array.length; i++);
ready
For loop with length in variable (HTMLColection)
for(var i=0, l=elm_array.length;i<l; i++);
ready
Normal for loop (Selectbox options)
for(var i=0; i<selectBox.options.length; i++);
 
ready
For loop with length in variable (Selectbox options)
for(var i=0, l=selectBox.options.length;i<l; i++);
ready
Normal for loop (short array)
for(var i=0; i<short_array.length; i++);
 
ready
For loop with length in variable (short array)
for(var i=0, l=short_array.length; i<l; 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 Jakub Mareda on