Javascript - what happens when I create an element in an array

Viewed 71

I am able to insert a value at an arbitrary index outside of the bounds of the array like so.

> const a = []
undefined
> a[999] = true
true
> a
[ <999 empty items>, true ]

I suspect that v8 is not creating 999 empty items under the hood and Arrays work more like Objects and instead we are creating a hidden class which has one key which is the key 999 at offset 0. Is this correct?

1 Answers

From https://v8.dev/blog/fast-properties

Arrays [] and Objects {} are both JSObjects.

The difference is that array-indexed items populate the elements store. Adding array-indexed properties does not create a new HiddenClass.

In sparsely populated arrays like arr[9999] = 'foo' v8 creates a "custom descriptor" in "dictionary mode" to avoid the memory waste of creating 10k empty entries. Array operations in dictionary mode will be significantly slower than contiguous arrays.

Related