0

I searched for this question but the answers I got not solve my question . Here is my question , I have a array with 10 members .

Js Code

var array = [1,2,3,4,5,6,7,8,9,10];

Loop 1:

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

Loop 2

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

Loop 3

for(var i=0;i<array.length;i++){}

I know there is a major performance difference between 1 and 3 . But , is there any performance difference between 1 and 2 ? .

kannanrbk
  • 6,964
  • 13
  • 53
  • 94
  • 1
    Why don't you test it for your self? =) – Mario S Nov 01 '12 at 12:07
  • There is no difference between 1 and 2 except you've just written an extra line in loop 2, where you have'nt in loop 3 – polin Nov 01 '12 at 12:09
  • See http://stackoverflow.com/questions/500431/javascript-variable-scope for lots of information about JavaScript variable scope. – Barmar Nov 01 '12 at 12:13
  • With older browsers you would see a speed boost with _loop1_ or _loop2_, but with modern day browsers it does not matter. – epascarello Nov 01 '12 at 12:22

4 Answers4

0

No, there isn't any difference. Javascript will hoist variables.

So code1 will be:

var i, len;
for (i=0, len=array.lengh; i<len; i++) {};

code2 will be

var i, len;
len = array.lengh;
for (i=0; i<len; i++) {};

The difference is only where to put the len=array.length

xdazz
  • 158,678
  • 38
  • 247
  • 274
0

There shouldn't be any noticeable difference, although the parsing logic has one more token to parse in example 2.

Shorter is better: var a,b,c,d; should be faster than

var a; var b; var c; var d;
Anirudh Ramanathan
  • 46,179
  • 22
  • 132
  • 191
Aki Suihkonen
  • 19,144
  • 1
  • 36
  • 57
0

Loop-1 and Loop-2 both are same because of there is one time Initialize of var len so no difference in performance .

Hardik Lotiya
  • 371
  • 3
  • 9
  • 28
0

Javascript has function scope, not block scope (excluding the new let syntax). Since a for loop is not a function it does not create a new scope, which means

for (var i...) { ... }

is exactly the same as

var i...
for (...) { ... }

However, the conditional statement of a for loop is re-evaluated every iteration in javascript, meaning this

for(var i=0;i<array.length;i++){}

will need to evaluate array.length many times, whereas this

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

once evaluates it once. It is faster, theoretically, but it is such a micro-optimization that it does not really matter.

jbabey
  • 45,965
  • 12
  • 71
  • 94