str.to!Enum performance

Per Nordlöw per.nordlow at gmail.com
Wed Sep 9 10:54:14 UTC 2026


On Monday, 7 September 2026 at 15:22:12 UTC, realhet wrote:
> Hi,
>
> I've compared 2 ways of converting enum identifier strings to 
> enum value:
> - implemented with a manual associative array: 45ms
> - implemented by std.conv.to: `name.to!Enum()`: 1299ms

One hotspot is the call to `NoDuplicates` at

https://github.com/dlang/phobos/blob/master/std/conv.d#L1109

If you know that your enum doesn't contain any duplicates you can 
use my

```d
/++ Faster replacement of `std.conv.to!(string)` for enum `T` 
with unique members. +/
string toStringUnique(T)(in T arg) nothrow @nogc if (is(T == 
enum)) {
	final switch (arg) {
		foreach (member; __traits(allMembers, T)) { // instead of way 
slower `EnumMembers`
		case __traits(getMember, T, member):
			return member;
		}
	}
}
pure nothrow @safe @nogc unittest {
	static enum E : ubyte { a = 0, b = 1 }
	assert(E.a.toStringUnique() == "a");
	assert(E.a.toStringUnique() == "a");
}
```

.


More information about the Digitalmars-d-learn mailing list