1. 程式人生 > >新版 C# 高效率程式設計指南

新版 C# 高效率程式設計指南

## 前言 C# 從 7 版本開始一直到如今的 9 版本,加入了非常多的特性,其中不乏改善效能、增加程式健壯性和程式碼簡潔性、可讀性的改進,這裡我整理一些使用新版 C# 的時候個人推薦的寫法,可能不適用於所有的人,但是還是希望對你們有所幫助。 注意:本指南適用於 .NET 5 或以上版本。 ## 使用 ref struct 做到 0 GC C# 7 開始引入了一種叫做 `ref struct` 的結構,這種結構本質是 `struct` ,結構儲存在棧記憶體。但是與 `struct` 不同的是,該結構不允許實現任何介面,並由編譯器保證該結構永遠不會被裝箱,因此不會給 GC 帶來任何的壓力。相對的,使用中就會有不能逃逸出棧的強制限制。 `Span` 就是利用 `ref struct` 的產物,成功的封裝出了安全且高效能的記憶體訪問操作,且可在大多數情況下代替指標而不損失任何的效能。 ```csharp ref struct MyStruct { public int Value { get; set; } } class RefStructGuide { static void Test() { MyStruct x = new MyStruct(); x.Value = 100; Foo(x); // ok Bar(x); // error, x cannot be boxed } static void Foo(MyStruct x) { } static void Bar(object x) { } } ``` ## 使用 stackalloc 在棧上分配連續記憶體 對於部分效能敏感卻需要使用少量的連續記憶體的情況,不必使用陣列,而可以通過 `stackalloc` 直接在棧上分配記憶體,並使用 `Span` 來安全的訪問,同樣的,這麼做可以做到 0 GC 壓力。 `stackalloc` 允許任何的值型別結構,但是要注意,`Span` 目前不支援 `ref struct` 作為泛型引數,因此在使用 `ref struct` 時需要直接使用指標。 ```csharp ref struct MyStruct { public int Value { get; set; } } class AllocGuide { static unsafe void RefStructAlloc() { MyStruct* x = stackalloc MyStruct[10]; for (int i = 0; i < 10; i++) { *(x + i) = new MyStruct { Value = i }; } } static void StructAlloc() { Span x = stackalloc int[10]; for (int i = 0; i < x.Length; i++) { x[i] = i; } } } ``` ## 使用 Span 操作連續記憶體 C# 7 開始引入了 `Span`,它封裝了一種安全且高效能的記憶體訪問操作方法,可用於在大多數情況下代替指標操作。 ```csharp static void SpanTest() { Span x = stackalloc int[10]; for (int i = 0; i < x.Length; i++) { x[i] = i; } ReadOnlySpan str = "12345".AsSpan(); for (int i = 0; i < str.Length; i++) { Console.WriteLine(str[i]); } } ``` ## 效能敏感時對於頻繁呼叫的函式使用 SkipLocalsInit C# 為了確保程式碼的安全會將所有的區域性變數在宣告時就進行初始化,無論是否必要。一般情況下這對效能並沒有太大影響,但是如果你的函式在操作很多棧上分配的記憶體,並且該函式還是被頻繁呼叫的,那麼這一消耗的副作用將會被放大變成不可忽略的損失。 因此你可以使用 `SkipLocalsInit` 這一特性禁用自動初始化區域性變數的行為。 ```csharp [SkipLocalsInit] unsafe static void Main() { Guid g; Console.WriteLine(*&g); } ``` 上述程式碼將輸出不可預期的結果,因為 `g` 並沒有被初始化為 0。另外,訪問未初始化的變數需要在 `unsafe` 上下文中使用指標進行訪問。 ## 使用函式指標代替 Marshal 進行互操作 C# 9 帶來了函式指標功能,該特性支援 managed 和 unmanaged 的函式,在進行 native interop 時,使用函式指標將能顯著改善效能。 例如,你有如下 C++ 程式碼: ```cpp #define UNICODE #define WIN32 #include extern "C" __declspec(dllexport) char* __cdecl InvokeFun(char* (*foo)(int)) { return foo(5); } ``` 並且你編寫了如下 C# 程式碼進行互操作: ```csharp [DllImport("./Test.dll")] static extern string InvokeFun(delegate* unmanaged[Cdecl] fun); [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] public static IntPtr Foo(int x) { var str = Enumerable.Repeat("x", x).Aggregate((a, b) => $"{a}{b}"); return Marshal.StringToHGlobalAnsi(str); } static void Main(string[] args) { var callback = (delegate* unmanaged[Cdecl])(delegate*)&Foo; Console.WriteLine(InvokeFun(callback)); } ``` 上述程式碼中,首先 C# 將自己的 `Foo` 方法作為函式指標傳給了 C++ 的 `InvokeFun` 函式,然後 C++ 用引數 5 呼叫該函式並返回其返回值到 C# 的呼叫方。 注意到上述程式碼還用了 `UnmanagedCallersOnly` 這一特性,這樣可以告訴編譯器該方法只會從 unmanaged 的程式碼被呼叫,因此編譯器可以做一些額外的優化。 使用函式指標產生的 IL 指令非常高效: ```msil ldftn native int Test.Program::Foo(int32) stloc.0 ldloc.0 call string Test.Program::InvokeFun(method native int *(int32)) ``` 除了 unmanaged 的情況外,managed 函式也是可以使用函式指標的: ```csharp static void Foo(int v) { } unsafe static void Main(string[] args) { delegate* managed fun = &Foo; fun(4); } ``` 產生的程式碼相對於原本的 Delegate 來說更加高效: ```msil ldftn void Test.Program::Foo(int32) stloc.0 ldc.i4.4 ldloc.0 calli void(int32) ``` ## 使用模式匹配 有了`if-else`、`as`和強制型別轉換,為什麼要使用模式匹配呢?有三方面原因:效能、魯棒性和可讀性。 為什麼說效能也是一個原因呢?因為 C# 編譯器會根據你的模式編譯出最優的匹配路徑。 考慮一下以下程式碼(程式碼 1): ```csharp int Match(int v) { if (v > 3) { return 5; } if (v < 3) { if (v > 1) { return 6; } if (v > -5) { return 7; } else { return 8; } } return 9; } ``` 如果改用模式匹配,配合 `switch` 表示式寫法則變成(程式碼 2): ```csharp int Match(int v) { return v switch { > 3 => 5, < 3 and > 1 => 6, < 3 and > -5 => 7, < 3 => 8, _ => 9 }; } ``` 以上程式碼會被編譯器編譯為: ```csharp int Match(int v) { if (v > 1) { if (v <= 3) { if (v < 3) { return 6; } return 9; } return 5; } if (v > -5) { return 7; } return 8; } ``` 我們計算一下平均比較次數: 程式碼 | 5 | 6 | 7 | 8 | 9 | 總數 | 平均 -|-|-|-|-|-|-|- 程式碼 1 | 1 | 3 | 4 | 4 | 2 | 14 | 2.8 程式碼 2 | 2 | 3 | 2 | 2 | 3 | 12 | 2.4 可以看到使用模式匹配時,編譯器選擇了更優的比較方案,你在編寫的時候無需考慮如何組織判斷語句,心智負擔降低,並且程式碼 2 可讀性和簡潔程度顯然比程式碼 1 更好,有哪些條件分支一目瞭然。 甚至遇到類似以下的情況時: ```csharp int Match(int v) { return v switch { 1 => 5, 2 => 6, 3 => 7, 4 => 8, _ => 9 }; } ``` 編譯器會直接將程式碼從條件判斷語句編譯成 `switch` 語句: ```csharp int Match(int v) { switch (v) { case 1: return 5; case 2: return 6; case 3: return 7; case 4: return 8; default: return 9; } } ``` 如此一來所有的判斷都不需要比較(因為 `switch` 可根據 HashCode 直接跳轉)。 編譯器非常智慧地為你選擇了最佳的方案。 那魯棒性從何談起呢?假設你漏掉了一個分支: ```csharp int v = 5; var x = v switch { > 3 => 1, < 3 => 2 }; ``` 此時編譯的話,編譯器就會警告你漏掉了 `v` 可能為 3 的情況,幫助減少程式出錯的可能性。 最後一點,可讀性。 假設你現在有這樣的東西: ```csharp abstract class Entry { } class UserEntry : Entry { public int UserId { get; set; } } class DataEntry : Entry { public int DataId { get; set; } } class EventEntry : Entry { public int EventId { get; set; } // 如果 CanRead 為 false 則查詢的時候直接返回空字串 public bool CanRead { get; set; } } ``` 現在有接收型別為 `Entry` 的引數的一個函式,該函式根據不同型別的 `Entry` 去資料庫查詢對應的 `Content`,那麼只需要寫: ```csharp string QueryMessage(Entry entry) { return entry switch { UserEntry u => dbContext1.User.FirstOrDefault(i => i.Id == u.UserId).Content, DataEntry d => dbContext1.Data.FirstOrDefault(i => i.Id == d.DataId).Content, EventEntry { EventId: var eventId, CanRead: true } => dbContext1.Event.FirstOrDefault(i => i.Id == eventId).Content, EventEntry { CanRead: false } => "", _ => throw new InvalidArgumentException("無效的引數") }; } ``` 更進一步,假如 `Entry.Id` 分佈在了資料庫 1 和 2 中,如果在資料庫 1 當中找不到則需要去資料庫 2 進行查詢,如果 2 也找不到才返回空字串,由於 C# 的模式匹配支援遞迴模式,因此只需要這樣寫: ```csharp string QueryMessage(Entry entry) { return entry switch { UserEntry u => dbContext1.User.FirstOrDefault(i => i.Id == u.UserId) switch { null => dbContext2.User.FirstOrDefault(i => i.Id == u.UserId)?.Content ?? "", var found => found.Content }, DataEntry d => dbContext1.Data.FirstOrDefault(i => i.Id == d.DataId) switch { null => dbContext2.Data.FirstOrDefault(i => i.Id == u.DataId)?.Content ?? "", var found => found.Content }, EventEntry { EventId: var eventId, CanRead: true } => dbContext1.Event.FirstOrDefault(i => i.Id == eventId) switch { null => dbContext2.Event.FirstOrDefault(i => i.Id == eventId)?.Content ?? "", var found => found.Content }, EventEntry { CanRead: false } => "", _ => throw new InvalidArgumentException("無效的引數") }; } ``` 就全部搞定了,程式碼非常簡潔,而且資料的流向一眼就能看清楚,就算是沒有接觸過這部分程式碼的人看一下模式匹配的過程,也能一眼就立刻掌握各分支的情況,而不需要在一堆的 `if-else` 當中梳理這段程式碼到底幹了什麼。 ## 使用記錄型別和不可變資料 `record` 作為 C# 9 的新工具,配合 `init` 僅可初始化屬性,為我們帶來了高效的資料互動能力和不可變性。 消除可變性意味著無副作用,一個無副作用的函式無需擔心資料同步互斥問題,因此在無鎖的並行程式設計中非常有用。 ```csharp record Point(int X, int Y); ``` 簡單的一句話等價於我們寫了如下程式碼,幫我們解決了 `ToString()` 格式化輸出、基於值的 `GetHashCode()` 和相等判斷等等各種問題: ```csharp internal class Point : IEquatable { private readonly int x; private readonly int y; protected virtual Type EqualityContract => typeof(Point); public int X { get => x; set => x = value; } public int Y { get => y; set => y = value; } public Point(int X, int Y) { x = X; y = Y; } public override string ToString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append("Point"); stringBuilder.Append(" { "); if (PrintMembers(stringBuilder)) { stringBuilder.Append(" "); } stringBuilder.Append("}"); return stringBuilder.ToString(); } protected virtual bool PrintMembers(StringBuilder builder) { builder.Append("X"); builder.Append(" = "); builder.Append(X.ToString()); builder.Append(", "); builder.Append("Y"); builder.Append(" = "); builder.Append(Y.ToString()); return true; } public static bool operator !=(Point r1, Point r2) { return !(r1 == r2); } public static bool operator ==(Point r1, Point r2) { if ((object)r1 != r2) { if ((object)r1 != null) { return r1.Equals(r2); } return false; } return true; } public override int GetHashCode() { return (EqualityComparer.Default.GetHashCode(EqualityContract) * -1521134295 + EqualityComparer.Default.GetHashCode(x)) * -1521134295 + EqualityComparer.Default.GetHashCode(y); } public override bool Equals(object obj) { return Equals(obj as Point); } public virtual bool Equals(Point other) { if ((object)other != null && EqualityContract == other.EqualityContract && EqualityComparer.Default.Equals(x, other.x)) { return EqualityComparer.Default.Equals(y, other.y); } return false; } public virtual Point Clone() { return new Point(this); } protected Point(Point original) { x = original.x; y = original.y; } public void Deconstruct(out int X, out int Y) { X = this.X; Y = this.Y; } } ``` 注意到 `x` 與 `y` 都是 `readonly` 的,因此一旦例項建立了就不可變,如果想要變更可以通過 `with` 建立一份副本,於是這種方式徹底消除了任何的副作用。 ```csharp var p1 = new Point(1, 2); var p2 = p1 with { Y = 3 }; // (1, 3) ``` 當然,你也可以自己使用 `init` 屬性表示這個屬性只能在初始化時被賦值: ```csharp class Point { public int X { get; init; } public int Y { get; init; } } ``` 這樣一來,一旦 `Point` 被建立,則 `X` 和 `Y` 的值就不會被修改了,可以放心地在並行程式設計模型中使用,而不需要加鎖。 ```csharp var p1 = new Point { X = 1, Y = 2 }; p1.Y = 3; // error var p2 = p1 with { Y = 3 }; //ok ``` ## 使用 readonly 型別 上面說到了不可變性的重要性,當然,`struct` 也可以是隻讀的: ```csharp readonly struct Foo { public int X { get; set; } // error } ``` 上面的程式碼會報錯,因為違反了 `X` 只讀的約束。 如果改成: ```csharp readonly struct Foo { public int X { get; } } ``` 或 ```csharp readonly struct Foo { public int X { get; init; } } ``` 則不會存在問題。 `Span` 本身是一個 `readonly ref struct`,通過這樣做保證了 `Span` 裡的東西不會被意外的修改,確保不變性和安全。 ## 使用區域性函式而不是 lambda 建立臨時委託 在使用 `Expression>` 作為引數的 API 時,使用 lambda 表示式是非常正確的,因為編譯器會把我們寫的 lambda 表示式編譯成 Expression Tree,而非直觀上的函式委託。 而在單純只是 `Func<>`、`Action<>` 時,使用 lambda 表示式恐怕不是一個好的決定,因為這樣做必定會引入一個新的閉包,造成額外的開銷和 GC 壓力。從 C# 8 開始,我們可以使用區域性函式很好的替換掉 lambda: ```csharp int SomeMethod(Func fun) { if (fun(3) > 3) return 3; else return fun(5); } void Caller() { int Foo(int v) => v + 1; var result = SomeMethod(Foo); Console.WriteLine(result); } ``` 以上程式碼便不會導致一個多餘的閉包開銷。 ## 使用 ValueTask 代替 Task 我們在遇到 `Task` 時,大多數情況下只是需要簡單的對其進行 `await` 而已,而並不需要將其儲存下來以後再 `await`,那麼 `Task` 提供的很多的功能則並沒有被使用,反而在高併發下,由於反覆分配 `Task` 導致 GC 壓力增加。 這種情況下,我們可以使用 `ValueTask` 代替 `Task`: ```csharp async ValueTask Foo() { await Task.Delay(5000); return 5; } async ValueTask Caller() { await Foo(); } ``` 由於 `ValueTask` 是值型別結構,因此不會在堆上分配記憶體,於是可以做到 0 GC。 ## 實現解構函式代替建立元組 如果我們想要把一個型別中的資料提取出來,我們可以選擇返回一個元組,其中包含我們需要的資料: ```csharp class Foo { private int x; private int y; public Foo(int x, int y) { this.x = x; this.y = y; } public (int, int) Deconstruct() { return (x, y); } } class Program { static void Bar(Foo v) { var (x, y) = v.Deconstruct(); Console.WriteLine($"X = {x}, Y = {y}"); } } ``` 上述程式碼會導致一個 `ValueTuple` 的開銷,如果我們將程式碼改成實現解構方法: ```csharp class Foo { private int x; private int y; public Foo(int x, int y) { this.x = x; this.y = y; } public void Deconstruct(out int x, out int y) { x = this.x; y = this.y; } } class Program { static void Bar(Foo v) { var (x, y) = v; Console.WriteLine($"X = {x}, Y = {y}"); } } ``` 則不僅省掉了 `Deconstruct()` 的呼叫,同時還沒有任何的額外開銷。你可以看到實現 Deconstruct 函式並不需要讓你的型別實現任何的介面,從根本上杜絕了裝箱的可能性,這是一種 0 開銷抽象。另外,解構函式還能用於做模式匹配,你可以像使用元組一樣地使用解構函式(下面程式碼的意思是,當 `x` 為 3 時取 `y`,否則取 `x + y`): ```csharp void Bar(Foo v) { var result = v switch { Foo (3, var y) => y, Foo (var x, var y) => x + y, _ => 0 }; Console.WriteLine(result); } ``` ## 總結 在合適的時候使用 C# 的新特性,不但可以提升開發效率,同時還能兼顧程式碼質量和執行效率的提升。 但是切忌濫用。新特性的引入對於我們寫高質量的程式碼無疑有很大的幫助,但是如果不分時宜地使用,可能會帶來反效果。 希望本文能對各位開發者使用新版 C# 時帶來一定的幫助,感謝閱讀。