Jon*_*eet 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);
Run Code Online (Sandbox Code Playgroud)

它更接近了.

如果你使用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位整数,这非常便宜.如果你想要对文化敏感的检查,并且性能对你来说特别重要,那就是我使用的过载.


Mar*_*ell 6

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

9156ms; chk: 50000000
6887ms; chk: 50000000
Run Code Online (Sandbox Code Playgroud)

试验台:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)


dom*_*mer 5

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