Contact MeContact Me

geek thread

Wednesday, March 05, 2008

Since some people have gotten tired of staring at my last post, and also since it's some whacky hour in the middle of the night when I should be sleeping, but ain't, I decided to share some work-related geekery.

This is probably stupid and you probably already know about this, but... You know that one bit of coding advice that's been going around about how you should initialize a local variable to the length of an array and use that in your "for" loop condition instead of accessing the length property on the array every iteration? Yeah. That one. Well, a couple colleagues and I were curious if this practice applied to all languages. Long story short, it seems that generally speaking, modern compilers (e.g., C#, VB, Java) should make such optimizations for you and to do so in those languages may be superfluous and only serve to make the code harder to read. However, such manual tweaking is still a good practice if you're developing Javascript for web pages (being that there is currently no smart JIT optimization going on under the hood of your typical browser today).

A compact, clean method of doing this involves initializing the length variable along with the iterator in the for loop construct:

for (var i = 0, len = myArray.length; i < len; i++) {}

Not only is this compact, but it also scopes the variable "len" to the loop itself, meaning it's eligible for garbage collection immediately after the loop is done iterating.

As for compiled languages (and even non-compiled languages), there are still options for speeding up array access in a "for" loop. One that I thought was interesting, but really makes app logic tough to follow, is initializing the iterator with the length of the array minus one, then counting backwards.

for (var i = myArr.length - 1; i >= 0; i--) {}

That really just buys you some extra cycles during the initialization of the loop, but not throughout subsequent iterations, and as I said, it's hard to immediately determine the purpose of that loop. One situation where you might get a noticeable increase in performance using that construct is when iterating through a large jagged multi-dimensional array. Like anyone ever does that.

Anyway, that's what you get for complaining about stale posts on my blog.

Labels: , ,



statCollector