StaticArray: Array on the Stack

github repo: GitHub - nagayev/static-array-proposal: Ecmascript proposal

Static array proposal

Champion

Looking for a champion.

Status

Stage 0, discussing the idea.

Motivation

In system languages like C or D user can create arrays with constant size like

int main(){
  int a[25];
  return 0;
}

Such arrays creates on the stack, not on the heap.
These means allocation takes less time.

So I suggest add to ECMAScript object StaticArray with Array like API excluding possibility to change Array's size.

Polyfills

As StaticArray is just Array, but located at the stack we user can use usual Array.

Hi @nagayev

For many JS engines allocating an array is more complex than knowing its length. They also optimise the object based on the values that are inserted (e.g int/floats).

If an object is short lived it is also likely to be allocated in the ‘nursery’ which is a fast bump allocator. So there may not be a big gain in using the stack here.

2 Likes

@aclaymore Thank you for your response.

Blockquote
If an object is short lived it is also likely to be allocated in the ‘nursery’ which is a fast bump allocator.

It's an interesting fact, I haven't known it. But what about objects with long life?
Maybe this optimization is still relevant for such cases.

If it's long-lived, you couldn't allocate it on the stack at all (or you'd have a problem).

I wouldn't be a fan of stack-based allocations either, because you'll have to deal with problems like this somehow, and there really isn't any pretty solution to this that doesn't go against the intuition of how arrays work.

function doThing(callback) {
  const myStackArray = <createStackArraySomehow>
  callback(myStackArray)
}

// elsewhere
let array = [] // Set it to an initial value
doThing(stackArray => array = stackArray)
console.log(array) // What happens?
1 Like