Which of the following two is more efficient? (Or maybe is there a third option that's better still?)
string val = "AStringValue"; if (val.Equals("astringvalue", StringComparison.InvariantCultureIgnoreCase))
OR
if (val.ToLowerCase() == "astringvalue")
?
The equalsIgnoreCase() method compares two strings, ignoring lower case and upper case differences. This method returns true if the strings are equal, and false if not. Tip: Use the compareToIgnoreCase() method to compare two strings lexicographically, ignoring case differences.
Comparing strings in a case insensitive manner means to compare them without taking care of the uppercase and lowercase letters. To perform this operation the most preferred method is to use either toUpperCase() or toLowerCase() function. Example 1: This example uses toUpperCase() function to compare two strings.
The strcasecmp() function compares, while ignoring differences in case, the string pointed to by string1 to the string pointed to by string2.
tf = strncmpi( s1,s2 , n ) compares up to n characters of s1 and s2 , ignoring any differences in letter case. The function returns 1 ( true ) if the two are identical and 0 ( false ) otherwise.
If you're looking for efficiency, use this:
string.Equals(val, "astringvalue", StringComparison.OrdinalIgnoreCase)
Ordinal comparisons can be significantly faster than culture-aware comparisons.
ToLowerCase
can be the better option if you're doing a lot of comparisons against the same string, however.
As with any performance optimization: measure it, then decide!
The first one is the correct one, and IMHO the more efficient one, since the second 'solution' instantiates a new string instance.
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