erichynds

Hi, I'm Eric Hynds, a front-end website developer living outside of Boston, Massachusetts. I'm passionate about developing functional, standard-compliant, and user-friendly websites.

Archive for the ‘JavaScript’ Category

JavaScript Loop Performance: Caching the ‘.length’ Property of an Array

Wednesday, December 9th, 2009

I was reading this article from SitePoint earlier about how inefficient the JavaScript is behind Google’s new Closure library, and saw some interesting discussion about caching an array’s length property before entering a ‘for’ loop. This is what I’m talking about:

// uncached length property
for(var x=0; x < myArray.length; x++){}
 
// cached length property
for(var x=0, len=myArray.length; x < len; x++){}

I saw this tip and didn’t think twice about it; I’ve always been told that caching the length property is indeed faster. I then saw a couple comments saying otherwise:

(more…)