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. cannot auto ptr = &e; (just cannot auto 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 compilation enum might expected lower, , binary smaller.
  • there surprising difference arrays. enum uint[2] e = [0, 1]; , immutable uint[2] = [0, 1]; access enum, e.g. e[0], can orders of magnitude slower immutable array, e.g. i[0], arrays e , i bigger. because immutable array, normal array lookup to, say, global variable. enum looks array gets created every time before gets used, e.g. inside function global enum (don't ask me, why, compiler seems replace appearance value in case, too). have never tried guess same applies enum 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

Popular posts from this blog

java - SNMP4J General Variable Binding Error -

windows - Python Service Installation - "Could not find PythonClass entry" -

Determine if a XmlNode is empty or null in C#? -