Reputation: 381
I am learning JavaScript and I see in some books/tutorial this:
myvariable = myArray.length;
for(i = 0; i < myVariable; i++){
doSomething;
}
What's the difference if I write it like this (I mean if I don't create a variable that holds the length of my array and I use myArray.length
Directly in the for
loop.
for(i = 0; i < myArray.length; i++)
{
doSomething;
}
Which one is better?
P.S: sorry for my bad English it's not my native language.
Thank you.
Upvotes: 0
Views: 2019
Reputation: 19275
Approved answer is wrong. There is actually a slight performance advantage to not storing length in a variable because the storing statement operation creates an overhead.
Also note that ES6 offers for/of which has better syntax when you don't need the array index but that one is significantly slower.
See the comparison here https://jsperf.com/storing-length/1
I'm comparing 3 different versions:
function f1(arr) {
let l = arr.length, res=0;
for(let i=0; i < l; i++) res+=arr[i];
return res;
}
function f2(arr) {
let res=0;
for(let i=0; i< arr.length; i++) res+=arr[i];
return res;
}
function f3(arr) {
let res=0;
for(const a of arr) res+=a;
return res;
}
When using a large sample, f1 is ~20% slower than f2, f3 is ~60% slower.
Upvotes: 0
Reputation: 19772
There is no functional difference with the given code.
There is a slight performance difference (negligible in most cases) in how you declare the variables that are in the for
statement.
When doing this:
for(var i = 0; i < someArray.length; i++)
var i
and someArray.length
are evaluated every iteration. So the total time, d
, it take the loop to occur is the time, t
, it takes to evaluate a variable, multiplied by the number of iterations, i
, of your loop:
d = t*i
Thus, as stated early, this difference will be negligible in most cases. It takes less code to write it the first way, but doing it this way will lower d
:
var i = 0,
len = someArray.length;
for( ; i<len; i++)
However, sometimes evaluating the length of someArray
every iteration is necessary due to possible changes in the length of someArray
(for example, when removing elements from someArray
):
for(var i = 0; i<someArray.length; i++) {
someArray.splice(someArray.length - 1, 1);
}
This will remove the last element of someArray
, and if you don't recompute the length of someArray
for every iteration of the loop, some browsers will throw an error.
To see some examples of how you can write the same loop in many different ways (as well as see the performance differences), see this jsperf (a JavaScript performance test).
Upvotes: 2