First, disclaimer that I have a shallow understanding of heap and stack and allocations. Given that, here is my basic understanding of StaticArrays: They are appropriate when there are lots of small arrays involved because StaticArrays use Tuples underneath, which live in the stack rather than heap. This is more efficient because there are no “allocations” when writing to the stack and reading from the stack is faster (or maybe I am wrong about the allocations bit there).
I am not sure how the compiler knowing the size of the arrays comes into play. If storing data in the heap, I understand that the program can set aside a fixed amount of memory (pre-allocate). Does the notion of pre-allocation apply to the stack as well?
Probably most importantly, how does the information about size get passed from the type signature to the compiler? I understand that the type system will create different types for each Size
in StaticArrays{Size}
, but how does the compiler know to use Size
to decide how much memory to pre-allocate?
I would imagine that having static arrays would be useful even with big arrays for the following reasons:
- it means the compiler doesn’t have to brace for the arrays changing size when there is no need
- it means, in certain situations, the compiler can be confident about indices being within bound just by looking at the type. So bound errors can be caught at compile time (I believe this is how Rust works?). I believe bound checking only occurs at runtime?
- beyond performance, there are cases where it is nice to have a gaurentee that the size of the container is not mutable. And we might not need to do linear algebra with it, just basic arithmatic. So even something basic like what Rust has would be good to have.
So why do we not have StaticArrays that are appropriate for arrays of all sizes?