digitalmars.D.learn - What does to!someEnum(string) lower to? Comparing speed to
- JR (15/15) Mar 01 2014 In my pet project I'm casting a lot of strings to named enum
- Adam D. Ruppe (5/5) Mar 01 2014 enum to string uses a switch if possible (src/phobos/std/conv.d
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?)
Mar 01 2014
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