So in C# the switch statement only supports integral types (not Guids), so a simple O(1) comparison table doesn't look possible.
What is the most computationally efficient way to match on a Guid
At first I thought
if(gMyGuid == new Guid("VALUE"))
else if (gMyGuid == new Guid("VALUE2")
else if (gMyGuid == new Guid("VALUE3")
...
else if (gMyGuid == new Guid("VALUEn")
However by doing this I'm creating a new instance of the Guid each time for a comparison. I could convert the Guid to a string then compare on the string but the string comparison is a pretty long string for comparison.
Any advise is gratefully received.
ToString(string format) returns a string representation of the value of this Guid instance, according to the provided format specifier. Examples: guidVal. ToString() or guidVal.
So the answer is "yes", it will always be the same length.
The Parse method trims any leading or trailing white space from input and converts the string representation of a GUID to a Guid value. This method can convert strings in any of the five formats produced by the ToString(String) and ToString(String, IFormatProvider) methods, as shown in the following table.
A GUID is a 16-byte (128-bit) number, typically represented by a 32-character hexadecimal string.
You can create a System.Collections.Generic.Dictionary
<Guid, ...>
where ...
is something useful to you.
Upon program startup, fill the dictionary with the guids and values that you need to recognize.
Then, use the TryGetValue
method of the dictionary to retrieve a value by its guid.
I haven't stated anything literal for ...
because I don't know what you want to do with the guids. Maybe you want to run some function, then a method pointer (Func<T>
or something like that) might be appropriate, or otherwise an interface type that provides the method you want to invoke. This depends on the context/purpose of that guid comparing code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With