D Language Gotchas

qznc qznc at web.de
Tue Nov 5 22:26:57 PST 2013


On Wednesday, 6 November 2013 at 04:57:57 UTC, Jonathan M Davis 
wrote:
> On Tuesday, November 05, 2013 13:27:54 Jacob Carlborg wrote:
>> On 2013-11-05 12:16, Meta wrote:
>> > One gotcha relates to enums. Writing `enum a = [0, 1, 2]` is 
>> > a really
>> > bad idea, because everywhere you use a, it constructs a new 
>> > array at
>> > runtime. The [0, 1, 2] is "pasted in", and you'll have a 
>> > bunch of
>> > allocations you didn't expect. This doesn't just happen with 
>> > arrays, but
>> > that's the most common case. What *is* okay is using string 
>> > enums, as
>> > strings are a bit special due to being immutable.
>> 
>> Isn't the problem rather that [0, 1, 2] allocates in the first 
>> place,
>> regardless if an enum is used or not.
>
> In most cases, array literals need to allocate, regardless of 
> whether they're
> an enum or not. The cases where they don't need to allocate 
> (e.g. when
> initializing a static array) shouldn't allocate, but an array 
> literal by
> itself is a dynamic array, and pretty much has to allocate in 
> most cases in
> order to be safe. Having an enum which is an array literal 
> rather than making
> it an immutable constant then results in allocations that you 
> might not want,
> but that's not really the literal's fault.

Can you work around that? Maybe something like:

   enum a = immutable([0, 1, 2]);


More information about the Digitalmars-d mailing list