i\'m doing some javascript coding and I was wondering if the length method is \"precomputed\", or remembered by the JS engine.
So, the question is:
If I\'m c
All major interpreters provide efficient accessors for the lengths of native arrays, but not for array-like objects like NodeLists.
"Efficient looping in Javascript"
Test / Browser Firefox 2.0 Opera 9.1 Internet Explorer 6 Native For-Loop 155 (ms) 121 (ms) 160 (ms) ... Improved Native While-Loop 120 (ms) 100 (ms) 110 (ms)
"Efficient JavaScript code" suggests
for( var i = 0; i < document.getElementsByTagName('tr').length; i++ ) { document.getElementsByTagName('tr')[i].className = 'newclass'; document.getElementsByTagName('tr')[i].style.color = 'red'; ... }
var rows = document.getElementsByTagName('tr'); for( var i = 0; i < rows.length; i++ ) { rows[i].className = 'newclass'; rows[i].style.color = 'red'; ... }
Neither of these are efficient.
getElementsByTagName
returns a dynamic object, not a static array. Every time the loop condition is checked, Opera has to reassess the object, and work out how many elements it references, in order to work out thelength
property. This takes a little more time than checking against a static number.