The explanation for a dense array that I read from a few pages seem to be in contradiction to one another. I\'d like some help understanding what it is.
While some l
"Dense" is in opposition to "sparse", and generally is used when talking about storage. For example, this array is dense:
a = [undefined, undefined, 2]
It can be stored in memory exactly like that: a sequence of three locations, the first two being undefined
, the third being 2
.
This array is sparse:
a = []
a[100000000] = 100000000
It is not stored in memory as a sequence of 100000001 locations, as it would be horribly inefficient. It is definitely not 100000000
places of undefined
followed by 100000000
. Rather, it just says 100000000th one is 100000000
, and there is no space allocated to the first 100000000 elements.
(Actually, try to do this with 2
instead of 100000000
, and you'll notice a curious thing: Chrome will display the dense array as [undefined, undefined, 2]
, but the sparse one as [undefined × 2, 2]
.)
Those articles say you can create an array being dense. This means that, at the time of creation, such arrays are dense, since in arrays like:
var a = new Array("foo", "bar", "baz");
var b = [2, 3, 5];
every element is set: from 0 to length-1, there is no undefined value. Or better said: every position from 0 to length-1 was assigned a value (even if the value is, actually, undefined
).
However, you can make those arrays not dense anymore, by doing something like this:
a[20] = "bat";
That array, which was dense, is not dense anymore since the elements 0 1 2 and 20 (unlike elements in 3 to 19) are set to a value (this array has 4 elements, not 21).