What is the fastest way to compare a string with an array of strings in C#2.0
While comparing the two function, in a loop repeted 500'000'000 times, strcmp execute too much fast, about x750 times faster. The execution time of that function is 3.058s , while strcmp only 0.004s .
You can compare and sort string arrays with relational operators, just as you can with numeric arrays. Use == to determine which elements of two string arrays are equal.
Using Arrays. equals(array1, array2) methods − This method iterates over each value of an array and compare using equals method. Using Arrays. deepEquals(array1, array2) methods − This method iterates over each value of an array and deep compare using any overridden equals method.
You can't compare strings in C with ==, because the C compiler does not really have a clue about strings beyond a string-literal.
What kind of comparison do you want? Do you want to know if the given string is in the array?
bool targetStringInArray = array.Contains(targetString);
do you want an array of comparison values (positive, negative, zero)?
var comparisons = array.Select(x => targetString.CompareTo(x));
If you're checking for containment (i.e. the first option) and you're going to do this with multiple strings, it would probably be better to build a HashSet<string>
from the array:
var stringSet = new HashSet<string>(array);
if (stringSet.Contains(firstString)) ...
if (stringSet.Contains(secondString)) ...
if (stringSet.Contains(thirdString)) ...
if (stringSet.Contains(fourthString)) ...
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