enum value vs. immutable
Jonathan M Davis
jmdavisProg at gmx.com
Mon Dec 2 23:30:46 PST 2013
On Monday, December 02, 2013 06:57:32 CJS wrote:
> I was reading the enum page of Ali Çehreli's (excellent) D book
> (http://ddili.org/ders/d.en/enum.html), and I'm confused by an
> enum value (not enum type), such as
> enum secondsPerDay = 60 * 60 * 24;
> In that situation I would have used an immutable variable. Is
> there any reason to prefer enum vs. immutable when defining
> constants?
enum doesn't create a variable, so if all you really want is for the value to
be used and don't care about having an actual variable, there's really no
reason to use an immutable variable. Also, enum has the advantage that it
_has_ to be known at compile time even if it's a local variable, so its value
with be determined at compile time, not runtime, which is almost always an
advantage.
The main situations where you should prefer an immutable variable are for
arrays and AAs or for any type or situation where the value needs to be
determined at runtime or where it would be better if it were. The main problem
with arrays and AAs and enums, is that you end up allocating a new one every
time the enum is used, which won't happen with a variable and isn't a problem
for other types of enums (as any other type which would be allocated on the
heap can't be an enum). Strings are an exception with regards to arrays as
string literals end up in a special place in memory rather than being
duplicated, so you don't end up with an allocation every time you use it.
Overall though, it's better to use enum for constants. Using a variable just
creates extra overhead (minimal though it may be).
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list