How do I use CTFE to generate an immutable associative array at compile time?

Jacob Carlborg via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Feb 22 00:00:36 PST 2017


On 2017-02-21 23:49, H. S. Teoh via Digitalmars-d-learn wrote:

> That may appear to work, but I would *strongly* recommend against it,
> because what happens when you use enum with an AA, is that the AA will
> be created *at runtime*, *every single time* it is referenced.  (It is
> as if you copy-n-pasted the entire AA into the code each time you
> reference the enum.)  Which will introduce ridiculous amounts of
> redundant work at runtime and cause a big performance penalty.

You can use an enum to declare the AA and then assign it to an immutable 
variable using "static this". The you would only use to the immutable 
variable and never the enum.

enum aa = [1 : 2];

immutable int[int] iaa;

static this()
{
     iaa = aa;
}

-- 
/Jacob Carlborg


More information about the Digitalmars-d-learn mailing list