Why is function isprefix faster than Startswith in C#?

前端 未结 4 695
一生所求
一生所求 2021-02-04 03:10

Does anyone know why C# (.NET)\'s StartsWith function is considerably slower than IsPrefix?

4条回答
  •  无人及你
    2021-02-04 03:21

    I think it's mostly fetching the thread's current culture.

    If you change Marc's test to use this form of 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);
    

    it comes a lot closer.

    If you use s1.StartsWith(s2, StringComparison.Ordinal) it's a lot faster than using CompareInfo.IsPrefix (depending on the CompareInfo of course). On my box the results are (not scientifically):

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

    Obviously that's because it's really just comparing 16 bit integers at each point, which is pretty cheap. If you don't want culture-sensitive checking, and performance is particularly important to you, that's the overload I'd use.

提交回复
热议问题