Dot-Net

為什麼函式是前綴比 C# 中的 Startswith 快?

  • April 4, 2009

有誰知道為什麼 C# (.NET) 的StartsWith函式比IsPrefix慢很多?

我認為它主要是獲取執行緒的目前文化。

如果您更改 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
  • 比較.IsPrefix(s1, s2): 5200ms
  • s1.StartsWith(s2, StringComparison.Ordinal): 1393ms

顯然這是因為它實際上只是在每個點比較 16 位整數,這非常便宜。如果您想要對文化敏感的檢查,並且性能對您來說特別重要,那麼這就是我要使用的重載。

引用自:https://stackoverflow.com/questions/717855