Conrad said:
Never call the Array constructor/factory with a single numeric
argument N. The outcome is either an array with N elements with the
`undefined' value (which eat up memory to no purpose),
Why should
var x = new Array(10000);
eat any more memory than
var x = [];
?
or an array with one element with value N.
As long as the argument is an integer in the supported range, it has to
be used to set the length property, not to add any elements. Are there
any implementations that got this wrong?
Firefox <= 2 would create elements with value undefined.
in Firefox 2,
'2' in new Array(10)
resulted true. Fixed in FF3.
Initializing an array's length can have a minor (maybe negligible)
performance improvement.
This is because an Array has a specialized [[Put]] method. It is as follows:
| 1. Call the [[CanPut]] method of A with name P.
| 2. If Result(1) is false, return.
| 3. If A doesn't have a property with name P, go to step 7.
| 4. If P is "length", go to step 12.
| 5. Set the value of property P of A to V.
| 6. Go to step 8.
| 7. Create a property with name P, set its value to V and give it empty
| attributes.
| 8. If P is not an array index, return.
| 9. If ToUint32(P) is less than the value of the length property of A,
| then return.
| 10. Change (or set) the value of the length property of A to
| ToUint32(P)+ 1.
| 11. Return.
In step 9, there is a chance at early return, which would result in
skipping step 10 (and 11). This will happen when "ToUint32(P) is less
than the value of the length property of A".
This can be applied when creating a new Array that is the result of a
merge or union of two or more collections or is a subset of a collection
(such as a filtering function like a custom getElementsByClassName).
When the resulting array is populated in a loop, set the array's length,
populate the array in the loop while maintaining the index of the last
added element, then after the loop, trim the array.
var max_possible_length = 1000000,
a = new Array(max_possible_length),
condition;
for(var i = 0, c = 0; i < max_possible_length; i++) {
condition = i % 7 === 0;
if(condition) {
a[c] = i;
c++;
}
}
a.length = c;
The loop keeps track of a counter |c|. This is the number of items added
to the array. After the loop is finished, the array is trimmed by
setting its length to |c|.
Though the performance improvement is almost negligible.
Garrett