immutability - enum vs immutable in D -
what's difference between
enum = 2; enum s = "hello";
and
immutable = 2; immutable s = "hello";
in d 2.0?
an enum
user-defined type, not variable. enum e = 2;
short-hand enum : int { e = 2 }
(i.e. anonymous enum 1 member e
), see the documentation. definition, members of anonymous enum placed current scope. so, e
type member placed current scope, behaves literal. immutable = 2;
on other hand creates variable i
of type int.
this difference has couple of consequences:
enum e
have no memory location , no address (is no lvalue), since neither type nor members have address. i.e. cannotauto ptr = &e;
(just cannotauto ptr = &2;
).immutable i
on other hand normal variable (just immutable).- as discussed jonathan, immutable variables can initialized @ compile time or @ run-time, whereas type (with members defining type) must known @ compile time.
- the compiler can replace appearances of
e
2
.i
has create memory location (although optimizing compiler might able avoid sometimes). reason, workload during compilationenum
might expected lower, , binary smaller. - there surprising difference arrays.
enum uint[2] e = [0, 1];
,immutable uint[2] = [0, 1];
accessenum
, e.g.e[0]
, can orders of magnitude slowerimmutable
array, e.g.i[0]
, arrayse
,i
bigger. becauseimmutable
array, normal array lookup to, say, global variable.enum
looks array gets created every time before gets used, e.g. inside function globalenum
(don't ask me, why, compiler seems replace appearance value in case, too). have never tried guess same appliesenum
strings , other non-trivial types.
to sum up: when use compile-time constants, take enum
unless constants arrays or need memory location other reason.
Comments
Post a Comment