What is the difference between enum and shared immutable?

Jan Hönig hrominium at gmail.com
Thu Oct 29 08:13:42 UTC 2020


On Wednesday, 28 October 2020 at 22:07:06 UTC, H. S. Teoh wrote:
> [...]
>
> An enum only exists at compile-time, and does not occupy any 
> space. Each time it's referenced, a new instance of the value 
> is created.  (This is why it's a bad idea to use enum with an 
> array literal, because every time it's referenced you get a new 
> copy of the array.)
>
> A shared immutable is initialized at compile-time, and occupies 
> space in the object file / runtime memory. It's also a single 
> instance, and referencing it causes a load of this instance at 
> runtime.  It's not copied unless it's a by-value type, so an 
> array literal will get stored as an array in the executable, 
> and every time you reference it you get a slice of it instead 
> of a copy.
>
>
> T

(thanks to you and Mike btw :)

Is there some rule of thumb when to use what?
I judge that using enum will slow down the compilation process, 
but might increase performance. So for a small struct, or array 
enum is completelty fine.
Large arrays should then use immutable, let's say when they are 
larger than 1kb?

Regarding the shared keyword, I am not sure if immutables are 
shared per default. I thought they are not.


More information about the Digitalmars-d-learn mailing list