Although the array is an object in JavaScript, there is no good reason to iterate for in
through the array using loops. Instead, there are good reasons not to use for in
traversal arrays.
Note: Arrays in JavaScript are not associative arrays . Only objects in JavaScript manage the correspondence of key values. But associative arrays are kept in order, and objects are not .
Because for in
loops enumerate all the properties on the prototype chain, the only way to filter them is to use a hasOwnProperty
function, so it can be for
many times slower than the normal loop.
Traverse
To achieve the best performance of traversing arrays, it is recommended to use a classic for
loop.
var list = [1, 2, 3, 4, 5, ...... 100000000];for(var i = 0, l = list.length; i < l; i++) { console.log(list[i]);}
The above code has a handle, which is l = list.length
to cache the length of the array.
Although length
it is a property of an array, it has a performance cost to access it in each loop. perhaps the latest JavaScript engine has been optimized for this, but we can't guarantee that our code will run on top of these recent engines.
In fact, not using cached array lengths is much slower than cached versions.
length
Property
length
The getter method of the property will simply return the length of the array, and the setter will truncate the array.
var foo = [1, 2, 3, 4, 5, 6];foo.length = 3;foo; // [1, 2, 3]foo.length = 6;foo; // [1, 2, 3]
Note: the value in Firebug foo
is: [1, 2, 3, undefined, undefined, undefined]
But the result is not accurate, if you look at the results in Chrome's console foo
, you will find this: [1, 2, 3]
because in JavaScript is undefined
a variable, note that the variable is not a keyword, so the meaning of the above two results is completely different.
// 译者注:为了验证,我们来执行下面代码,看序号 5 是否存在于 foo 中。5 in foo; // 不管在 Firebug 或者 Chrome 都返回 falsefoo[5] = undefined;5 in foo; // 不管在 Firebug 或者 Chrome 都返回 true
length
setting a smaller value truncates the array, but increasing the value of the length
property does not affect the group.
Conclusion
For better performance, it is recommended to use a normal for
loop and cache the properties of the array length
. Using for in
traversal arrays is considered a bad code habit and tends to produce errors and cause performance problems.
Array ① array traversal and properties