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 ehave 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 ion 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
e2.ihas create memory location (although optimizing compiler might able avoid sometimes). reason, workload during compilationenummight 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 slowerimmutablearray, e.g.i[0], arrayse,ibigger. becauseimmutablearray, normal array lookup to, say, global variable.enumlooks 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 appliesenumstrings , 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