C# string 為不可變類型。ToUpper()、Replace()、Substring() 等操作皆會配置新字串物件,產生 GC 壓力。高頻熱路徑 (如每秒百萬次日誌格式化) 可透過 unsafe 直接操作字串內部字元陣列,實現原地修改。
using System;
public class UnsafeStringMutator
{
public static void Main()
{
string str = "hello";
ToUpperUnsafe(str);
Console.WriteLine(str); // 輸出: HELLO (原字串被修改!)
}
private static unsafe void ToUpperUnsafe(string str)
{
// fixed: 釘住字串在記憶體中,防止 GC 移動
fixed (char* pFixed = str)
{
for (char* p = pFixed; *p != '\0'; p++)
{
*p = char.ToUpper(*p); // 直接修改字元
}
}
}
}
| 關鍵字 | 作用 | 注意事項 |
|---|---|---|
unsafe | 標記方法/區塊允許指標運算 | 編譯需 /unsafe 旗標 (專案屬性 → Build → Allow unsafe code) |
fixed | 釘住受控物件位址,防止 GC 壓縮堆疊時移動 | 僅在 fixed 區塊內有效;區塊結束自動解釘 |
char* | 指向字元的指標 | 字串內部以 \0 結尾 (C 風格),可安全迴圈 |
csc.exe:csc /unsafe Program.cs。<AllowUnsafeBlocks>true</AllowUnsafeBlocks> 在 .csproj。這是「核武級」技術,嚴禁濫用。
unsafe 代碼需要 FullTrust,沙箱/受限環境 (如 Blazor WebAssembly、Unity IL2CPP 某些平台) 禁止執行。fixed 阻止 GC 壓縮,長時間釘選大型物件會造成堆疊碎片化。StringBuilder 內部緩衝區、ArrayPool 租用陣列)。GetWindowText),此時應用 StringBuilder 或 char[] 而非修改 managed string。| 需求 | 推薦做法 |
|---|---|
| 高效能字串建構 | StringBuilder / Span + ArrayPool |
| 原地修改緩衝區 | char[] / Memory / Span |
| 避免配置 | string.Create (C# 7.3+), ValueStringBuilder (內部類) |
| Interop 緩衝區 | StringBuilder (預設容量足夠) / byte[] + Marshal |
unsafe + fixed 修改字串展示了 C# 突破語言安全邊界的能力,但生產代碼極少合理使用場景。現代 Span/Memory/StringBuilder/ArrayPool 提供同等效能且保持記憶體安全與 GC 友善。理解原理、敬畏風險、選擇正統工具,才是專業開發者的態度。