Assigning global and static associative arrays
Jonathan M Davis
jmdavisProg at gmx.com
Sat Sep 1 02:14:48 PDT 2012
On Saturday, September 01, 2012 11:07:34 Philippe Sigaud wrote:
> > Using enum can be very useful, but I wouldn't use it for AAs at all, and
> > I'd be leery of using it for much in the way of arrays other than string
> > literals (since the string literals should avoid the memory allocations
> > that other array literals get). It's fine most other stuff, but for those
> > items, you need to be very wary of it or risk lots of unnecessary GC
> > allocations.
>
> I guess the rule to follow is not to use enum for anything with lots
> of allocation.
>
> Why do string literals have less memory allocations?
If I understand correctly, you end up with all uses of the same string literal
being the exact same chunk of memory, but I could be wrong. Let's see... Well,
this program seems to print the same thing 4 times
import std.stdio;
enum a = "hello";
enum b = "hello";
void main()
{
writeln(a.ptr);
writeln(a.ptr);
writeln(b.ptr);
writeln(b.ptr);
}
so it looks like not only do all instances of the same string enum use the
same memory, but another enum with the same string literal shares it as well.
So, only one is allocated. And on Linux at least, as I understand it, the
string literals go in ROM. But it may be that the above code functions
differently in Windows, since it _doesn't_ put string literals in ROM.
Regardless, you can contrast that with this
import std.stdio;
enum a = [1, 2, 3, 4, 5];
enum b = [1, 2, 3, 4, 5];
void main()
{
writeln(a.ptr);
writeln(a.ptr);
writeln(b.ptr);
writeln(b.ptr);
}
which prints 4 different addresses. So clearly, each use of an enum which is an
array literal allocates a new array.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list