Why is function isprefix faster than Startswith in C#?

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

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

4条回答
  •  青春惊慌失措
    2021-02-04 03:40

    Good question; for a test, I get:

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

    Test rig:

    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);
        }
    }
    

提交回复
热议问题