www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - What does to!someEnum(string) lower to? Comparing speed to

reply "JR" <zorael gmail.com> writes:
In my pet project I'm casting a lot of strings to named enum 

     enum Animal { Gorilla, Shark, Alien, Rambo, Dolphin }
     auto foo = "Dolphin";
     auto fooAsEnum = foo.to!Animal;

While micro-optimizing because it's fun, I see that it's much 
faster (by some factor of >3.5x) to do such casts as associative 
array lookups rather than by using std.conv.to as above. As in, 
populate an Animal[string] array with all enum members indexed by 
the strings of their names, allowing you to get the Animal you 
want via animalAA[foo] or (foo in animalAA).

In comparison, what code is generated from the foo.to!Animal 
cast? A big final switch? A long if-else-if-else chain?


(Can the compiler not generate such code instead?)
Mar 01 2014
parent "Adam D. Ruppe" <destructionator gmail.com> writes:
enum to string uses a switch if possible (src/phobos/std/conv.d 
line 844)

I think the code that does string to enum is on line 2194, which 
is a foreach { if {} } loop that never breaks; it always checks 
all of them.
Mar 01 2014