-1

Is there a difference in terms of performance between

for(x=0;x<data.list.length;x++){
//...
}

vs

var dList=data.list;

for(x=0;x<dList.length;x++){
//...
}

Many thanks

3 Answers3

1

Trivial enough not to worry about most of the time. Best practice says do something like this:

for(var x = 0, len = data.list.length; x < len; x++){
   //...
}

Even better if you count down to 0, but that's a different question.

  • Thanks Jeffman. This issue came up on our code review. And I just want to know if there's really a big performance improvement. I was told to use the second one (where to put it on a variable) but as you said it's a trivial. – voicemeoutdotcom Sep 30 '13 at 08:24
0

The only performance enhancement that you'll see in reality here is to store the length value so it doesn't need to reach into your data.list at every iteration for comparison.

int size = data.list.length;

for(x=0x<size;x++){
    //...
} 

As mentioned by others this, this is extremely trivial for 99.99999% of cases and even frowned upon when namespace is an issue. The general rule of thumb is the easier it is to read the better off you probably are.

rfoo
  • 1,160
  • 1
  • 12
  • 27
0

Let's give it a try.

first case:

var start = new Date();
var data = {};
data.list = Array(100000);
for(x=0;x<data.list.length;x++){
    data.list[x] = Math.sqrt(Math.pow(x, 7));
}
var finish = new Date();
console.log(finish - start + "ms"); //245ms

second case:

var start = new Date();
var data = {};
data.list = Array(100000);
var dList = data.list
for(x=0;x<dList.length;x++){
    dList[x] = Math.sqrt(Math.pow(x, 7));
}
var finish = new Date();
console.log(finish - start + "ms"); //251ms

but there's another way to increase performance:

var start = new Date();
var data = {};
data.list = Array(100000);
for(x = data.list.length; x--; ){
    data.list[x] = Math.sqrt(Math.pow(x, 7));
}
var finish = new Date();
console.log(finish - start + "ms"); //199ms

x-- returns decreasing number, and when it reaches zero its boolean value becomes false, so the loop stops. That works faster because the comparison with zero performs much faster than comparison with any other number.

Andrey Ozornin
  • 1,129
  • 1
  • 9
  • 24