Is it faster to compare strings with Regex with IgnoreCase or with the ToLower string method?

For such lines:

string s1 = "Abc";
string s2 = "ABC";

Which is faster:

Regex.Match(s1, s2, RegexOptions.IgnoreCase)

or

s1.ToLower() == s2.ToLower()

If they are the same or one is faster, then the other, so when is it better to use one over the other?

+3
source share
7 answers

The second is probably faster, but I would avoid both of these approaches.

Better to use a method string.Equalswith the corresponding argument StringComparison:

s1.Equals(s2, StringComparison.CurrentCultureIgnoreCase)

See how it works on the Internet: ideone

+8
source

Theoretically, comparing 2 lines should be faster; RegEx knows that they are pretty slow.

, s1 RegEx s2, ( , ), , .

, :)

+4

@Mark Byers .

, ToLower . .

s1.Equals(s2, StringComparison.CurrentCultureIgnoreCase) //#1
s1.ToLower() == s2.ToLower() //#2
s1.ToLowerInvariant() == s2.ToLowerInvariant() //#3

(2) (3) , . "" .

# 1, Hashtables

( )

+3

, Regex.Match(s1, s2, RegexOptions.IgnoreCase) . , s2 - ".*". Regex.Match true , s1!

+3

- . , , .

, , " ". - , , . , , .

+2

Comparison will be faster, but instead of converting to lower or upper case and then comparing, it is better to use equality comparison, which can be made case insensitive. For instance.

        s1.Equals(s2, StringComparison.OrdinalIgnoreCase)
0
source

The following is a small comparison of the three proposed methods:

Regex: 282ms ToLower: 67 ms Equal: 34 ms

public static void RunSnippet()
{
    string s1 = "Abc";
    string s2 = "ABC";

    // Preload
    compareUsingRegex(s1, s2);
    compareUsingToLower(s1, s2);
    compareUsingEquals(s1, s2);

    // Regex
    Stopwatch swRegex = Stopwatch.StartNew();
    for (int i = 0; i < 300000; i++) 
        compareUsingRegex(s1, s2);
    Console.WriteLine(string.Format("Regex: {0} ms", swRegex.ElapsedMilliseconds));

    // ToLower
    Stopwatch swToLower = Stopwatch.StartNew();
    for (int i = 0; i < 300000; i++) 
        compareUsingToLower(s1, s2);
    Console.WriteLine(string.Format("ToLower: {0} ms", swToLower.ElapsedMilliseconds));

    // ToLower
    Stopwatch swEquals = Stopwatch.StartNew();
    for (int i = 0; i < 300000; i++) 
        compareUsingEquals(s1, s2);
    Console.WriteLine(string.Format("Equals: {0} ms", swEquals.ElapsedMilliseconds));
}

private static bool compareUsingRegex(string s1, string s2) 
{
    return Regex.IsMatch(s1, s2, RegexOptions.IgnoreCase);
}

private static bool compareUsingToLower(string s1, string s2) 
{
    return s1.ToLower() == s2.ToLower();
}

private static bool compareUsingEquals(string s1, string s2) 
{
    return s1.Equals(s2, StringComparison.CurrentCultureIgnoreCase);
}
0
source

All Articles