I\'m fairly new to JS, and realize length is considered a property. But I received a comment to not use str.length in a loop:
for (i=0; i
W3Schools recommends that you use this:
l = arr.length;
for (i = 0; i < l; i++) {..}
instead of this:
for (i = 0; i < arr.length; i++) {...}
Claiming that:
The bad code accesses the length property of an array each time the loop is iterated.
The better code accesses the length property outside the loop, and makes the loop run faster.
Because w3schools is evil, let me quote from another source (Writing Efficient JavaScript - Nicholas C. Zakas).
... The important lesson to take from this information is to always store frequently accessed values in a local variable. Consider the following code:
function process(data){
if (data.count > 0){
for (var i=0; i < data.count; i++){
processData(data.item[i]);
}
}
}
...The function will run faster if this value is stored in a local variable and then accessed from there:
function process(data){
var count = data.count;
if (count > 0){
for (var i=0; i < count; i++){
processData(data.item[i]);
}
}
}
From here:
Most JavaScript engines use a dictionary-like data structure as storage for object properties - each property access requires a dynamic lookup to resolve the property's location in memory. This approach makes accessing properties in JavaScript typically much slower than accessing instance variables in programming languages like Java and Smalltalk.
In general some (or most) JavaScript engines use optimization techniques to improve the property access time like this one by V8.
Also, JavaScript string objects might be of a different nature as you cannot add properties dynamically to them. (which makes the dynamic lookup unnecessary.. I guess)
For string.length use any of the two code snippets. But for other object types or properties that do computations, then you have to benchmark your code performance first (or just store the value in a local variable).