Mutable enums

Jonathan M Davis jmdavisProg at gmx.com
Sun Nov 13 16:50:50 PST 2011


On Monday, November 14, 2011 02:16:57 so wrote:
> On Mon, 14 Nov 2011 02:09:40 +0200, Jonathan M Davis <jmdavisProg at gmx.com>
> 
> wrote:
> > It depends entirely on what you're trying to do. If you understand how
> > manifest constants work, then they can be quite advantageous. What you
> > probably really want for arrays though is not an enum but just a const
> > or
> > immutable module variable.
> > 
> > immutable a = [3, 1, 2];
> > 
> > Otherwise, you're allocating a new array every time you use the enum.
> > So, use
> > a manifest constant when you want to avoid having it take up any memory
> > but
> > don't care about whatever allocations may occur when it's used
> > (primitive
> > types such as ints being a prime example), whereas if you want an actual
> > memory location for the constant and/or want it to be allocated only
> > once,
> > then use variable rather than an enum.
> > 
> > - Jonathan M Davis
> 
> Wait a second, it is definitely a bug. You can't modify an enum.
> 
> "immutable a = [3, 1, 2];" is practically "enum a = [3, 1, 2];".

No. Those are two _very_ different things.

immutable a = [3, 1, 2];

creates a variable of type immutable(int[]). You takes up memory. You can take 
its address - e.g. &a. It exists even if you don't use it at all.

enum a = [3, 1, 2];

on the other hand, doesn't create any variable at all. It's what's called a 
manifest constant. It's a placeholder. It takes up no memory. You can't take 
its address. If you never use it, it doesn't end up in the generated program 
at all. Every use of a effectively copies the value of a to wherever its used. 
So,

enum a = [3, 1, 2];
sort(a);

is _identical_ to

sort([3, 1, 2]);

That means that if you use a in any code, it's copied in that code such that 
you could end up allocating a lot of memory that you didn't intend to if you 
heavily use manifest constants which are strings or arrays. But it also means 
that you get a new copy to use at each location, which can also be useful. And 
for types that don't end up on the heap (e.g. int), there's really no cost to 
it, and it actually is _more_ efficient (albeit marginally), since it avoids 
having to allocate any memory for the enum itself, since it's not a variable.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list