[Semi-OT] to!string(enumType)

Stefan Koch via Digitalmars-d digitalmars-d at puremagic.com
Thu May 18 15:31:47 PDT 2017


Hi,

I just took a look into commonly used functionality of Phobos.
Such as getting the string representation of a enum.

the following code:

import std.conv;
enum ET
{
   One,
   Two
}

static assert(to!string(ET.One) == "One");

takes about 220 milliseconds to compile.
creating a 7.5k object file

Using my -vcg-ast it becomes visible that it expands to ~17000 
lines of template-instantiations.
explaining both the compilation time and the size.

Compiling the following code:

string enumToString(E)(E v)
{
     static assert(is(E == enum), "emumToString is only meant for 
enums");
     mixin ({
     string result = "final switch(v) {\n";
     foreach(m;[__traits(allMembers, E)])
     {
         result ~= "\tcase E." ~ m ~ " :\n"
             ~ "\t\treturn \"" ~ m ~ "\";\n"
             ~ "\tbreak;\n";
     }
     return result ~ "}";
     } ());
}

private enum ET
{
   One,
   Two
}

static assert (enumToString(ET.One) == "One");

takes about 4 milliseconds to compile.
creating a 4.8k object file.

Granted this version will result in undefined behavior if you 
pass something like (cast(ET) 3) to it.
But the 55x increase in compilation speed is well worth it :)


More information about the Digitalmars-d mailing list