Performance of Switch case vs dictionary with delegates
-
For literals, the other alternative would be to use a UTF8 string literal:
ReadOnlySpan bytes = "ABCD"u8;
int value = System.Runtime.InteropServices.MemoryMarshal.Read(bytes);
// 0x44434241It's not going to compile to a single instruction, but it should be fairly well optimized.
"These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer
That solves the issue if you restrict yourself to 7-bit ASCII. Even for West European languages (such as Norwegian), a character may fill more than one octet. So if you step through a string 4 characters at a time, converting them to 32 bits, you will miss 8 bits here and there. Can lead to nasty, hard-to-debug errors when it happens with a customer on the other side of the earth, using a language with lots of multi-octet UTF8 characters.
Religious freedom is the freedom to say that two plus two make five.
-
That was added in C# 11, back in November 2022. :) UTF-8 string literals - C# feature specifications | Microsoft Learn[^]
"These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer