新版 C# 高效率編程指南

前言

C# 從 7 版本開始一直到現在的 9 版本,加入了很是多的特性,其中不乏改善性能、增長程序健壯性和代碼簡潔性、可讀性的改進,這裏我整理一些使用新版 C# 的時候我的推薦的寫法,可能不適用於全部的人,可是仍是但願對大家有所幫助。數據庫

注意:本指南適用於 .NET 5 或以上版本。編程

使用 ref struct 作到 0 GC

C# 7 開始引入了一種叫作 ref struct 的結構,這種結構本質是 struct ,結構存儲在棧內存。可是與 struct 不一樣的是,該結構不容許實現任何接口,並由編譯器保證該結構永遠不會被裝箱,所以不會給 GC 帶來任何的壓力。相對的,使用中就會有不能逃逸出棧的強制限制。數組

Span<T> 就是利用 ref struct 的產物,成功的封裝出了安全且高性能的內存訪問操做,且可在大多數狀況下代替指針而不損失任何的性能。安全

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<T> 來安全的訪問,一樣的,這麼作能夠作到 0 GC 壓力。閉包

stackalloc 容許任何的值類型結構,可是要注意,Span<T> 目前不支持 ref struct 做爲泛型參數,所以在使用 ref struct 時須要直接使用指針。併發

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<int> x = stackalloc int[10];
        for (int i = 0; i < x.Length; i++)
        {
            x[i] = i;
        }
    }
}

使用 Span 操做連續內存

C# 7 開始引入了 Span<T>,它封裝了一種安全且高性能的內存訪問操做方法,可用於在大多數狀況下代替指針操做。async

static void SpanTest()
{
    Span<int> x = stackalloc int[10];
    for (int i = 0; i < x.Length; i++)
    {
        x[i] = i;
    }

    ReadOnlySpan<char> str = "12345".AsSpan();
    for (int i = 0; i < str.Length; i++)
    {
        Console.WriteLine(str[i]);
    }
}

性能敏感時對於頻繁調用的函數使用 SkipLocalsInit

C# 爲了確保代碼的安全會將全部的局部變量在聲明時就進行初始化,不管是否必要。通常狀況下這對性能並無太大影響,可是若是你的函數在操做不少棧上分配的內存,而且該函數仍是被頻繁調用的,那麼這一消耗的反作用將會被放大變成不可忽略的損失。ide

所以你可使用 SkipLocalsInit 這一特性禁用自動初始化局部變量的行爲。函數

[SkipLocalsInit]
unsafe static void Main()
{
    Guid g;
    Console.WriteLine(*&g);
}

上述代碼將輸出不可預期的結果,由於 g 並無被初始化爲 0。另外,訪問未初始化的變量須要在 unsafe 上下文中使用指針進行訪問。高併發

使用函數指針代替 Marshal 進行互操做

C# 9 帶來了函數指針功能,該特性支持 managed 和 unmanaged 的函數,在進行 native interop 時,使用函數指針將能顯著改善性能。

例如,你有以下 C++ 代碼:

#define UNICODE
#define WIN32
#include <cstring>

extern "C" __declspec(dllexport) char* __cdecl InvokeFun(char* (*foo)(int)) {
    return foo(5);
}

而且你編寫了以下 C# 代碼進行互操做:

[DllImport("./Test.dll")]
static extern string InvokeFun(delegate* unmanaged[Cdecl]<int, IntPtr> 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]<int, nint>)(delegate*<int, nint>)&Foo;
    Console.WriteLine(InvokeFun(callback));
}

上述代碼中,首先 C# 將本身的 Foo 方法做爲函數指針傳給了 C++ 的 InvokeFun 函數,而後 C++ 用參數 5 調用該函數並返回其返回值到 C# 的調用方。

注意到上述代碼還用了 UnmanagedCallersOnly 這一特性,這樣能夠告訴編譯器該方法只會從 unmanaged 的代碼被調用,所以編譯器能夠作一些額外的優化。

使用函數指針產生的 IL 指令很是高效:

ldftn native int Test.Program::Foo(int32)
stloc.0
ldloc.0
call string Test.Program::InvokeFun(method native int *(int32))

除了 unmanaged 的狀況外,managed 函數也是可使用函數指針的:

static void Foo(int v) { }
unsafe static void Main(string[] args)
{
    delegate* managed<int, void> fun = &Foo;
    fun(4);
}

產生的代碼相對於本來的 Delegate 來講更加高效:

ldftn void Test.Program::Foo(int32)
stloc.0
ldc.i4.4
ldloc.0
calli void(int32)

使用模式匹配

有了if-elseas和強制類型轉換,爲何要使用模式匹配呢?有三方面緣由:性能、魯棒性和可讀性。

爲何說性能也是一個緣由呢?由於 C# 編譯器會根據你的模式編譯出最優的匹配路徑。

考慮一下如下代碼(代碼 1):

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):

int Match(int v)
{
    return v switch
    {
        > 3 => 5,
        < 3 and > 1 => 6,
        < 3 and > -5 => 7,
        < 3 => 8,
        _ => 9
    };
}

以上代碼會被編譯器編譯爲:

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 更好,有哪些條件分支一目瞭然。

甚至遇到相似如下的狀況時:

int Match(int v)
{
    return v switch
    {
        1 => 5,
        2 => 6,
        3 => 7,
        4 => 8,
        _ => 9
    };
}

編譯器會直接將代碼從條件判斷語句編譯成 switch 語句:

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 直接跳轉)。

編譯器很是智能地爲你選擇了最佳的方案。

那魯棒性從何談起呢?假設你漏掉了一個分支:

int v = 5;
var x = v switch
{
    > 3 => 1,
    < 3 => 2
};

此時編譯的話,編譯器就會警告你漏掉了 v 可能爲 3 的狀況,幫助減小程序出錯的可能性。

最後一點,可讀性。

假設你如今有這樣的東西:

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,那麼只須要寫:

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# 的模式匹配支持遞歸模式,所以只須要這樣寫:

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 僅可初始化屬性,爲咱們帶來了高效的數據交互能力和不可變性。

消除可變性意味着無反作用,一個無反作用的函數無需擔憂數據同步互斥問題,所以在無鎖的並行編程中很是有用。

record Point(int X, int Y);

簡單的一句話等價於咱們寫了以下代碼,幫咱們解決了 ToString() 格式化輸出、基於值的 GetHashCode() 和相等判斷等等各類問題:

internal class Point : IEquatable<Point>
{
    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<Type>.Default.GetHashCode(EqualityContract) * -1521134295 + EqualityComparer<int>.Default.GetHashCode(x)) * -1521134295 + EqualityComparer<int>.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<int>.Default.Equals(x, other.x))
        {
            return EqualityComparer<int>.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;
    }
}

注意到 xy 都是 readonly 的,所以一旦實例建立了就不可變,若是想要變動能夠經過 with 建立一份副本,因而這種方式完全消除了任何的反作用。

var p1 = new Point(1, 2);
var p2 = p1 with { Y = 3 }; // (1, 3)

固然,你也能夠本身使用 init 屬性表示這個屬性只能在初始化時被賦值:

class Point
{
    public int X { get; init; }
    public int Y { get; init; }
}

這樣一來,一旦 Point 被建立,則 XY 的值就不會被修改了,能夠放心地在並行編程模型中使用,而不須要加鎖。

var p1 = new Point { X = 1, Y = 2 };
p1.Y = 3; // error
var p2 = p1 with { Y = 3 }; //ok

使用 readonly 類型

上面說到了不可變性的重要性,固然,struct 也能夠是隻讀的:

readonly struct Foo
{
    public int X { get; set; } // error
}

上面的代碼會報錯,由於違反了 X 只讀的約束。

若是改爲:

readonly struct Foo
{
    public int X { get; }
}

readonly struct Foo
{
    public int X { get; init; }
}

則不會存在問題。

Span<T> 自己是一個 readonly ref struct,經過這樣作保證了 Span<T> 裏的東西不會被意外的修改,確保不變性和安全。

使用局部函數而不是 lambda 建立臨時委託

在使用 Expression<Func<>> 做爲參數的 API 時,使用 lambda 表達式是很是正確的,由於編譯器會把咱們寫的 lambda 表達式編譯成 Expression Tree,而非直觀上的函數委託。

而在單純只是 Func<>Action<> 時,使用 lambda 表達式恐怕不是一個好的決定,由於這樣作一定會引入一個新的閉包,形成額外的開銷和 GC 壓力。從 C# 8 開始,咱們可使用局部函數很好的替換掉 lambda:

int SomeMethod(Func<int, int> 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<T> 時,大多數狀況下只是須要簡單的對其進行 await 而已,而並不須要將其保存下來之後再 await,那麼 Task<T> 提供的不少的功能則並無被使用,反而在高併發下,因爲反覆分配 Task 致使 GC 壓力增長。

這種狀況下,咱們可使用 ValueTask<T> 代替 Task<T>

async ValueTask<int> Foo()
{
    await Task.Delay(5000);
    return 5;
}

async ValueTask Caller()
{
    await Foo();
}

因爲 ValueTask<T> 是值類型結構,所以不會在堆上分配內存,因而能夠作到 0 GC。

實現解構函數代替建立元組

若是咱們想要把一個類型中的數據提取出來,咱們能夠選擇返回一個元組,其中包含咱們須要的數據:

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<int, int> 的開銷,若是咱們將代碼改爲實現解構方法:

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):

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# 時帶來必定的幫助,感謝閱讀。

相關文章
相關標籤/搜索