RegexOptions.IgnoreCase,功能強大但效能較低。參考 KMP 思想,先轉大寫比對索引,再以 char[] 陣列一次建構結果,避免重複字串配置:
private static string ReplaceEx(string original, string pattern, string replacement)
{
int count = 0, position0 = 0, position1 = 0;
string upperString = original.ToUpper();
string upperPattern = pattern.ToUpper();
int inc = (original.Length / pattern.Length) * (replacement.Length - pattern.Length);
char[] chars = new char[original.Length + Math.Max(0, inc)];
while ((position1 = upperString.IndexOf(upperPattern, position0)) != -1)
{
for (int i = position0; i < position1; ++i) chars[count++] = original[i];
for (int i = 0; i < replacement.Length; ++i) chars[count++] = replacement[i];
position0 = position1 + pattern.Length;
}
if (position0 == 0) return original;
for (int i = position0; i < original.Length; ++i) chars[count++] = original[i];
return new string(chars, 0, count);
}
| 測試字串 | Regex | VB Replace | ReplaceEx | String.Replace |
|---|---|---|---|---|
| "AaBbCc" x1000 | 3.75 秒 | 1.46 秒 | 0.80 秒 | 0.18 秒 |
| "abcaBcabC" x1000 | 5.30 秒 | 2.50 秒 | 1.01 秒 | 0.23 秒 |
| "ABCabcAbCaBcAbcabCABCAbcaBC" x1000 | 13.59 秒 | 11.18 秒 | 1.70 秒 | 0.42 秒 |
結論:若需大小寫不敏感且追求效能,ReplaceEx 優於 Regex 與 VB Replace;若區分大小寫,內建 String.Replace 最快。