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
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
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.
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.
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.