What’s the Fastest Way to Code a Loop in JavaScript?
Date : 2008 07 28 Category : Tech & DevelopmentGregory Reimer, frontend engineer for sun.com, has written a barrage of tests to answer the question What's the Fastest Way to Code a Loop in JavaScript? specifically for large data sets:
I built a loop benchmarking test suite for different ways of coding loops in JavaScript. There are a few of these out there already, but I didn't find any that acknowledged the difference between native arrays and HTML collections. Since the underlying implementations are different (HTML collections for example lack the pop() and slice() methods, etc), benchmarks that don't test against both are probably missing important information.
My suspicions were confirmed. Accessing the length property is more expensive on HTML collections than on arrays, depending on the browser. In those cases, caching it made a huge difference. However, HTML collections are live, so a cached value may fail if the underlying DOM is modified during looping. On the other hand, HTML collections will never be sparse, so the best way to loop an HTML collection might just be to ignore the length property altogether and combine the test with the item lookup, since you have to do that anyway:
PLAIN TEXT JAVASCRIPT: // looping a dom html collection for (var i=0, node; node = hColl[i++];) { // do something with node }If you take a look at the results you will see that in general, reverse while loops are the fastest way to iterate a basic collection, e.g.:
PLAIN TEXT JAVASCRIPT: var i = arr.length; while (i--) {}Take a peak at the test suite.