User2
User2

Reputation: 591

Which is more efficient? (Variables for JavaScript loop)

To keep it simple, sat at my desk wondering if there is a difference in efficiency between (in JavaScript):

var i = 0;

for(i=0; i<Something.length; i++) foo();

for(i=0; i<Something.length; i++) foo();

And...

for(var i=0; i<Something.length; i++) foo();

for(var i=0; i<Something.length; i++) foo();

Upvotes: 2

Views: 170

Answers (2)

krasu
krasu

Reputation: 2037

This one will be faster, you will cache Something.length in variable so it will not be interpreted during loop:

for(var i=0, len = Something.length; i<len; i++) foo();

Here is a test

But moving var definition from loop will be really a bit faster without caching

Upvotes: 4

Ovilia
Ovilia

Reputation: 7310

I tried with 1000000 loops, the first runs for 2.7sec, the second runs for 2.418sec.

Apparently, the first one is faster.

But as JavaScript has no block scope, i in both cases will still be available out of the loop and you may have error if you forget to init it later.

Upvotes: 2

Related Questions