若 String.Split 能滿足分割需求,其性能顯著優於 Regex.Match。Regex 需編譯正則表達式、構建狀態機、回溯匹配,開銷大數量級。
| 操作 | 輸入 | Split 耗時 | Regex.Match 耗時 | 倍數差 |
|---|---|---|---|---|
| 單字符分割 | "a,b,c,d,e" | ~15 ns | ~120 ns | 8x |
| 多字符分割 | "a::b::c::d" | ~25 ns | ~150 ns | 6x |
| 複雜模式 (Regex 必須) | "a1b22c333d" | N/A | ~200 ns | — |
需要分割字符串
│
├─ 分隔符是否固定、單一/多字符、無正則元字符?
│ ├─ 是 → String.Split / String.Split(String[], StringSplitOptions)
│ │ ├─ 去除空項:.Split(new[]{","}, StringSplitOptions.RemoveEmptyEntries)
│ │ └─ 限制數量:.Split(',', 3) // 只分前 2 個逗號
│ │
│ └─ 否 (需模式匹配、捕獲組、邊界斷言、條件分割)
│ → Regex.Split / Regex.Matches
│ ├─ 預編譯:static readonly Regex _rx = new Regex(pattern, RegexOptions.Compiled);
│ ├─ 緩存 Regex 實例,避免重複編譯
│ └─ 複雜場景:如 "分號或換行符分割,但引號內的不分割"
// 1. 簡單分割:Split (首選)
string[] parts = line.Split(','); // 單字符
string[] parts = line.Split(new[] { "::" }, StringSplitOptions.RemoveEmptyEntries); // 多字符
// 2. 固定模式複用:靜態預編譯 Regex
private static readonly Regex CsvSplitter = new Regex(@"""(?:[^""]|"""")*""|[^,]+", RegexOptions.Compiled);
public static string[] SplitCsv(string line) {
return CsvSplitter.Matches(line).Cast().Select(m => m.Value.Trim('"')).ToArray();
}
// 3. 高性能場景:Span/Memory (NET Core 2.1+)
foreach (var part in line.AsSpan().Split(',')) { ... } // 無分配,極快
// 4. 避免熱路徑 new Regex()
❌ foreach(var s in list) { var m = Regex.Match(s, pattern); } // 每次編譯!
✅ static readonly Regex _rx = new Regex(pattern, RegexOptions.Compiled);
Split(String[], ...) 完美支持;能用 Split 絕不用 Regex。Split 是針對固定分隔符優化的原生操作,零分配 (Span)、分支預測友好、指令級優化。Regex 是處理「模式」的重型武器,僅在分隔符為正則模式時使用,並務必靜態預編譯緩存。