What does to!someEnum(string) lower to? Comparing speed to someEnum[string] AA lookups

JR zorael at gmail.com
Sat Mar 1 08:41:14 PST 2014


In my pet project I'm casting a lot of strings to named enum 
members.

     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?

http://dpaste.dzfl.pl/7e700a1053c0

(Can the compiler not generate such code instead?)


More information about the Digitalmars-d-learn mailing list