Fastest Loops in Javascript

I’m always interesting in Javascript and which constructs perform better than others. There are alot of funky things about this language, but for loops always seem to be a moving target for me.

I tend to stick with the regular var i = 0 loop, because it’s easy to understand:

for(var i = 0, l = something.length; i < l, i++) {
   // do something

But there are options, like this one:

var a;
while((a = arr[i++]) !== undefined) {

Which also seems to be the fastest construct, according to this site:

And the award for most inventive?

var arr2 = arr.slice(0);
while( (i = arr2.shift()) !== undefined ) {

My point is, there are alot of ways to skin a cat, it turns out, you can get significant performance boosts by googling to see if there’s not a better way to do things. Even if it’s something you’ve been doing for years and taking for granted.

Leave a Reply

Your email address will not be published. Required fields are marked *