What exactly is a dense array?

前端 未结 2 1030
[愿得一人]
[愿得一人] 2020-12-15 08:49

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

2条回答
  •  半阙折子戏
    2020-12-15 09:15

    "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].)

提交回复
热议问题