I’m working with some code that returns a code to indicate the type of user that they are (e.g. “A”, “B”, “C”, “D”, etc.). Each code corresponds to a specific role and/or scope (e.g. across the entire application or just for the object being worked on).
In some code that I’m looking at, I see calls to check if the user’s code is one of several in order to allow them to perform some action. So I see calls like:
//"B" would come from the database
string userCode = "B";
//some more work...
//if the user's code is either A or C...
if("AC".IndexOf(userCode) >= 0) {
//do work that allows the user to progress
} else {
//notify user they can't do this operation
}
Is this an efficient way of performing this check? Are there more efficient ways?
Thanks in advance!
Looking at the de-compiled code for
Contains(), it just callsIndexOf()withStringComparison.Ordinal, so I’d sayIndexOf()is most efficient (by a very small hair) i if used in the same way (Ordinal) since it has one less method call, butContains()is more readable and therefore more maintainable…As in all things, I’d go with what’s more readable and maintainable then splitting hairs on performance. Only do micro-optimization when you know there’s a bottleneck at this point.
UPDATE: Over 1,000,000 iterations:
So as you can see, very, very NEAR same. Once again, go with what’s more maintainable.
UPDATE 2: If your code is always a single char (not a 1-char string), IndexOf() is faster:
If you know your char codes are always a single char, it is about an order of magnitude faster to use
IndexOf()with a char argument.This is because
Contains(char value)is an extension method off ofIEnumerable<T>and not a first class method ofstring.But once again ~100 ms over 1,000,000 iterations is really, truly, quite negligible.