Is enum static?

monarch_dodra monarchdodra at gmail.com
Tue Aug 20 02:38:34 PDT 2013


On Monday, 19 August 2013 at 23:14:12 UTC, Jonathan M Davis wrote:
> On Monday, August 19, 2013 12:18:36 Borislav Kosharov wrote:
>> So if I want to have a string constant it is a lot better to
>> declare it as:
>> 
>> static immutable string MY_STRING = "Some string";
>> 
>> Because it won't be duplicated?
>
> Even if you copy-pasted "Some string" in your code thousands of 
> times, only
> one string is allocated, which is one of the advantages of 
> strings being
> immutable (the compiler can get away with allocating memory for 
> string
> literals only once). But other array literals _do_ result in a 
> new array
> allocated every time that they're in the code, and when you use 
> an enum, its
> value is copy-pasted every place that it's used, resulting in a 
> new allocation
> every time that it's used.
>
> So, using string enums is fine, but using other arrays as enums 
> is usually a
> bad idea.
>
> - Jonathan M Davis

I think one exception to this is when you index an enum. EG:
enum vals=[1, 2, 3, 0];

auto a = vals[i];

Here, the compiler will not make an allocation (at least, it 
didn't last time I tested)


More information about the Digitalmars-d-learn mailing list