What's the point of static arrays ?
simen.kjaras at gmail.com
Fri Jul 10 11:20:17 UTC 2020
On Friday, 10 July 2020 at 10:13:23 UTC, wjoe wrote:
> However stack memory needs to be allocated at program start. I
> don't see a huge benefit in allocation speed vs. heap
> pre-allocation, or is there?
> I mean 1 allocation vs 2 isn't going to noticeably improve
> overall performance.
You seem to still be thinking of static arrays as the same kind
of "thing" as a dynamic array. They're (usually) more like ints
or structs than containers: they're generally small, they're
often parts of other structures or classes, and they're fairly
often the element type of a larger dynamic array. For instance, a
bitmap image could be a byte, with dynamic dimensions
3840x2160. If instead of byte we used byte, not only would
things grind to a halt immediately, we'd also be using massively
When you're using a static array on the stack, it's usually just
because it's more convenient to say `int buffer;` than `auto
buffer = new int;`. The fact it may be faster is mostly a
side benefit. Also, even if you did preallocate such a buffer,
there's the overhead of remembering how to get to it, the work of
setting it up, probably a function call on use, etc. The
alternative is terser, built-in, more obvious to maintainers,
pretty unlikely to overflow the stack, and very unlikely to be
slower. Allocating a multi-MiB static array on the stack is a
sign that you're using your screwdriver as a hammer, and there
are probably better ways to do what you're trying to do.
> What happens here exactly ?
It creates a dynamic array that points to the data in the static
array. It's just shorthand for a[0..$]:
int a = [1,2,3,4];
auto b = a;
assert(b.length == 4);
assert(b.ptr == &a);
auto c = a[0..$];
assert(b is c);
More information about the Digitalmars-d-learn