为什么函数isprefix比C#中的Startswith更快?

时间:2009-04-04 21:34:08

标签: .net performance string startswith

有谁知道为什么C#(。NET)的StartsWith函数比IsPrefix慢得多?

4 个答案:

答案 0 :(得分:28)

我认为这主要取决于该线程目前的文化。

如果您更改Marc的测试以使用此String.StartsWith形式:

    Stopwatch watch = Stopwatch.StartNew();
    CultureInfo cc = CultureInfo.CurrentCulture;
    for (int i = 0; i < LOOP; i++)
    {
        if (s1.StartsWith(s2, false, cc)) chk++;
    }
    watch.Stop();
    Console.WriteLine(watch.ElapsedMilliseconds + "ms; chk: " + chk);

它更接近了。

如果您使用s1.StartsWith(s2, StringComparison.Ordinal),则比使用CompareInfo.IsPrefix要快得多(当然,取决于CompareInfo)。在我的方框上,结果是(不科学):

  • s1.StartsWith(s2):6914ms
  • s1.StartsWith(s2,false,culture):5568ms
  • compare.IsPrefix(s1,s2):5200ms
  • s1.StartsWith(s2,StringComparison.Ordinal):1393ms

显然那是因为它实际上只是在每个点比较16位整数,这非常便宜。如果您想要进行文化敏感检查,那么对您来说特别重要,那就是我使用的重载。

答案 1 :(得分:6)

好问题;为了测试,我得到:

9156ms; chk: 50000000
6887ms; chk: 50000000

试验台:

using System;
using System.Diagnostics;
using System.Globalization;    

class Program
{
    static void Main()
    {
        string s1 = "abcdefghijklmnopqrstuvwxyz", s2 = "abcdefg";

        const int LOOP = 50000000;
        int chk = 0;
        Stopwatch watch = Stopwatch.StartNew();
        for (int i = 0; i < LOOP; i++)
        {
            if (s1.StartsWith(s2)) chk++;
        }
        watch.Stop();
        Console.WriteLine(watch.ElapsedMilliseconds + "ms; chk: " + chk);

        chk = 0;
        watch = Stopwatch.StartNew();

        CompareInfo ci = CultureInfo.CurrentCulture.CompareInfo;
        for (int i = 0; i < LOOP; i++)
        {
            if (ci.IsPrefix(s1, s2)) chk++;
        }
        watch.Stop();
        Console.WriteLine(watch.ElapsedMilliseconds + "ms; chk: " + chk);
    }
}

答案 2 :(得分:5)

StartsWith内部调用IsPrefix。它在调用IsPrefix之前分配文化信息。

答案 3 :(得分:0)

查看IsPrefix的来源。问题是 - 在某些情况下,它会比StartsWith慢,只是因为它实际上使用了StartsWith并且进行了更多的操作。

    [System.Security.SecuritySafeCritical]  // auto-generated
    public unsafe virtual bool IsPrefix(String source, String prefix, CompareOptions options)
    { 
        if (source == null || prefix == null) {
            throw new ArgumentNullException((source == null ? "source" : "prefix"), 
                Environment.GetResourceString("ArgumentNull_String")); 
        }
        Contract.EndContractBlock(); 
        int prefixLen = prefix.Length;

        if (prefixLen == 0)
        { 
            return (true);
        } 

        if (options == CompareOptions.OrdinalIgnoreCase)
        { 
            return source.StartsWith(prefix, StringComparison.OrdinalIgnoreCase);
        }

        if (options == CompareOptions.Ordinal) 
        {
            return source.StartsWith(prefix, StringComparison.Ordinal); 
        } 

        if ((options & ValidIndexMaskOffFlags) != 0) { 
            throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag"), "options");
        }


        // to let the sorting DLL do the call optimization in case of Ascii strings, we check if the strings are in Ascii and then send the flag RESERVED_FIND_ASCII_STRING  to
        // the sorting DLL API SortFindString so sorting DLL don't have to check if the string is Ascii with every call to SortFindString. 

        return (InternalFindNLSStringEx(
                    m_dataHandle, m_handleOrigin, m_sortName, 
                    GetNativeCompareFlags(options) | Win32Native.FIND_STARTSWITH | ((source.IsAscii() && prefix.IsAscii()) ? RESERVED_FIND_ASCII_STRING : 0),
                    source, source.Length, 0, prefix, prefix.Length) > -1);
    }