Why are immutable array literals heap allocated?

Jonathan M Davis newsgroup.d at jmdavisprog.com
Fri Jul 5 23:05:32 UTC 2019


On Friday, July 5, 2019 10:25:10 AM MDT Nick Treleaven via Digitalmars-d-
learn wrote:
> On Thursday, 4 July 2019 at 11:06:36 UTC, Eugene Wissner wrote:
> >     static immutable arr = [1, 2];
> >
> > You have to spell it out that the data is static.
>
> Yes, I was wondering why the compiler doesn't statically allocate
> it automatically as an optimization.

It would have to be set up to store the literal somewhere else. Certainly,
it can't just put it on the stack, because that risks it going out of scope
and causing memory problems. It could theoretically be done with some types,
but it's more than simply optimizing the code. As it stands, AFAIK, string
literals are the only case where you avoid such allocations, and they get
put in a particular place in memory for that to work. Something similar
would have to be done with any other array literals where allocation was
being avoided (save maybe for a case where scope is used and, and the
compiler can statically verify that if it put it on the stack, it wouldn't
escape the scope). And if I understand correctly what's being done with
string literals, it requires that the value be known at compile time, in
which case, any array literals with variables or function calls or the like
couldn't work that way. Ultimately though, I think that what it comes down
to is that rather than the compiler figuring out which array literals it can
treat as special, it simply just knows that it can treat string literals
that way and does it with them and nothing else.

Another thing to consider is that optimizations shouldn't affect the
semantics. So, no matter what optimizations the compiler does with array
literals, that shouldn't affect whether the function can be @nogc. For it to
affect that, it would have to be something that was guaranteed by the
language's semantics regardless of whether any optimizations were being
done. So, even if an advanced optimizer really did figure out how to avoid
the GC allocations, that wouldn't help with @nogc. Rather, it would have to
be built into the semantics of the language.

- Jonathan M Davis





More information about the Digitalmars-d-learn mailing list