What's the point of static arrays ?
H. S. Teoh
hsteoh at quickfur.ath.cx
Thu Jul 9 16:21:41 UTC 2020
On Thu, Jul 09, 2020 at 12:12:06PM +0000, wjoe via Digitalmars-d-learn wrote:
> + The size is known at compile time.
> - Can neither grow nor shrink them
> - Can't append elements
> - Can't remove elements
Consider a 3D game in which you represent vectors as static arrays of 4
elements (homogenous representation). In this case, it's a plus to not
be able to append/remove elements, because the rest of the code expects
vectors that are exactly 4 elements long.
> - Can't slice them
> - Can't range them
Sure you can.
> - Assignment copies the whole array, as in int a; auto b = a;
Sometimes this is desirable. Consider the 3D game example. Suppose
you're given a vector and need to perform some computation on it. If it
were a dynamic array, you'd need to allocate a new array on the heap in
order to work on it without changing the original vector. With a static
array, it's passed by value to your function, so you just do what you
need to do with it, and when you're done, either discard it (== no work
because it's allocated on the stack) or return it (== return on the
stack, no allocations).
> - Size is limited by stack
> - Stack overflow issues
You *can* allocate static arrays on the heap, in which case they become
closer to dynamic arrays. Generally, the cases for which static arrays
are useful are when the size isn't huge; for huge arrays it makes more
sense to just use dynamic arrays.
You can also have classes that contain large static arrays: in this
case, the usefulness comes from having the array embedded in the class
object itself, rather than being a separate heap allocation + another
level of indirection.
> Considering the many downsides why would I ever want to choose a
> static over a dynamic array ?
It depends on your needs. If you know you're always going to be trading
in vectors of a fixed size, like 4-element vectors in aforementioned 3D
game, then there's no need to put extra GC (or whatever allocator)
pressure on your code, just trade in T. You also skip bounds checks
in many cases, since the length is known at compile-time. You get
by-value semantics, which is generally much easier to reason about than
by-reference semantics. You avoid an extra level of indirection, which
can matter in hotspots.
If your arrays are going to change in length, then static arrays aren't
what you need; just use dynamic arrays. They serve different purposes.
All men are mortal. Socrates is mortal. Therefore all men are Socrates.
More information about the Digitalmars-d-learn