What is the difference between enum and shared immutable?

H. S. Teoh hsteoh at quickfur.ath.cx
Thu Oct 29 13:46:05 UTC 2020


On Thu, Oct 29, 2020 at 08:13:42AM +0000, Jan Hönig via Digitalmars-d-learn wrote:
[...]
> 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.

Nah. The slowdown is practically indiscernible. You should be more
concerned about the semantics.


> So for a small struct, or array enum is completelty fine.

Actually, I'd recommend *never* to use enum with an array literal,
because it comes with a GC allocation *every single time it's
referenced*:

	enum E = [ 1 ]; // small array
	...
	auto arr = E; // GC allocation
	if (arr == E) { // another GC allocation
		return E; // yet another GC allocation
	}

Array constants should almost always use static immutable. That way,
they get allocated once in the executable, and every reference takes a
slice of them instead of incurring a GC allocation every single time.


> Large arrays should then use immutable, let's say when they are larger
> than 1kb?
[...]

I'd say array constants should *always* use immutable.

Use enum for by-value types like PODs and small structs -- because they
can be created in situ without incurring a GC allocation. Depending on
the architecture and size of the type, it might even compile into
instructions that create the value in CPU registers directly, without
allocating stack space for it. So that's something desirable for PODs
and small structs.


T

-- 
Why do conspiracy theories always come from the same people??


More information about the Digitalmars-d-learn mailing list