Reputation: 16438
Here is the code
example 1
for (var k = 0, l = value.length; k < l; k++, index++) {
// ...
}
example 2
var l = value.length;
for (var k = 0; k < l; k++, index++) {
// ...
}
In example 1, variable l is defined inside of the 'for' brackets, so does it mean l is being defined every time the loop goes through? If so then example 2 would be more efficient right?
Upvotes: 0
Views: 114
Reputation: 14046
I am surprised by the answers given here.
Example 1 is a well-known anti-pattern mentioned in many books and articles. It re-calculates l in every loop. Depending on how expensive this (or whatever other unnecessary) operation you put inside the for-call (except the 1st argument), the code may take much longer to execute.
Example 2 is better because the value of l
is calculated only once and is cached. Caching is a very important concept and this simple examples demonstrates it. Also it will work even if you change value
inside the loop, whereas the first Example could lead to unexpected results.
In my opinion, the only possible reason to use Example 1 is when you indeed need to recalculate l
for every loop, e.g. when the loop changes value
and you really want to update l
.
Upvotes: -1
Reputation: 10249
there is no efficiency difference in the snippets.
in the first snipet l = value.length is called once. just like k = 0
Upvotes: 2
Reputation: 15070
They are equal in speed. Nothing different.
But I recommand you to use example 2 because it is better to read.
Upvotes: 4