Fixed object arrays?

I would like to see a fixed-size object array to complement the fixed-size numeric arrays.

Dynamically-sized arrays are useful for general high-level use, but there are cases where a fixed-size object array would be extremely handy to help augment certain performance optimizations (especially with circular buffers) and better inform the engine of the intent of the code so it can be more properly optimized. Engines already use these or some similar construct internally for a lot as well, too. (Example)

This is technically possible today, in a hacky sort of way. Not sure if the browsers bother to optimize this case either. So, it would probably be better to have a dedicated array type for this, but thought I would point it out anyways.

const myArray = []
myArray.length = 5
myArray[0] = 'a'
console.log(myArray) // ['a', <empty>*4]
myArray.push('b') // Error!

V8 doesn't even currently optimize the obvious low hanging fruit of new Array(n).fill(null). If I could rely on engines to do event that little bit, I wouldn't be suggesting this in the first place.

1 Like

If you can't expect that, why would you expect a brand-new construct to be optimized sufficiently for your use cases?

It can't be resized, and so the idea is it memory-wise would be treated more like a typed array that just happens to also be usable as a GC root. Also, engines already use similar abstractions underneath quite broadly, so I don't see it as a major ask for them to make a few tweaks to expose it and subsequently copy over (with light modifications) the relevant typed array methods. (V8 in particular might not even need to create a new type for it if the length property is made an own property for consistency with traditional arrays.)

Maybe something like this could be achieved with Fixed-layout-objects
If one was dynamically created based on the length using eval.
Admittedly a bit on the hacky side and maybe no faster, or even slower than a regular array.

At the very least it feels somewhat in the same spirit as this other proposal?


Yeah, that could work well enough.