Community程式設計與開發github.com

類型設計效能

針對 .NET 型別設計進行效能最佳化。密封類別、使用唯讀結構、偏好靜態純函式、避免過早列舉,並選擇正確的集合類型。

類型設計效能 是什麼?

這項技能提供開發者一套完整的 .NET 型別設計準則,旨在最大化應用程式的執行效能。它涵蓋了從基礎的類別密封、結構與類別選擇,到進階的集合回傳型別、Span<T> 使用與 ValueTask 決策等關鍵領域。透過遵循這些原則,開發者可以讓 JIT 編譯器進行更積極的最佳化(如虛擬方法去虛擬化),減少記憶體配置與防禦性複製,並提升程式碼的可測試性與執行緒安全性。此技能支援所有現代 .NET 平台(包括 .NET 8+),其內容以具體的 C# 程式碼範例與清晰的比較表格呈現,讓開發者能立即應用在日常的型別設計與程式碼審查中,有效避免常見的效能反模式。

相容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/Aaronontheweb/dotnet-skills/tree/main/skills/csharp-type-design-performance

Installed? Explore more 程式設計與開發 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

型別設計效能最佳化

使用時機

請在以下情況使用此技能:

  • 設計新型別與 API 時
  • 審查程式碼中的效能問題時
  • 在 class、struct 和 record 之間做選擇時
  • 處理集合與可列舉物件時

核心原則

  1. 密封你的型別 - 除非明確設計為可繼承
  2. 偏好唯讀結構 - 適用於小型、不可變的實值型別
  3. 偏好靜態純函式 - 可獲得更好的效能與可測試性
  4. 延遲列舉 - 只在需要時才具體化
  5. 回傳不可變集合 - 從 API 邊界回傳

預設密封類別

密封類別能讓 JIT 進行去虛擬化,並清楚傳達 API 的設計意圖。

// 正確做法:密封非為繼承設計的類別
public sealed class OrderProcessor
{
    public void Process(Order order) { }
}

// 正確做法:密封記錄(它們本身就是類別)
public sealed record OrderCreated(OrderId Id, CustomerId CustomerId);

// 錯誤做法:未經充分理由就保持未密封狀態
public class OrderProcessor  // 可以被繼承 - 這是故意的嗎?
{
    public virtual void Process(Order order) { }  // Virtual = 較慢
}

優點:

  • JIT 可以對方法呼叫進行去虛擬化
  • 傳達「這不是擴充點」的意圖
  • 防止因意外繼承而導致的破壞性變更

針對實值型別使用唯讀結構

當結構為不可變時,應宣告為 readonly。這麼做可以防止防禦性複製。

// 正確做法:為不可變的實值型別使用唯讀結構
public readonly record struct OrderId(Guid Value)
{
    public static OrderId New() => new(Guid.NewGuid());
    public override string ToString() => Value.ToString();
}

// 正確做法:為小型、短生命週期的資料使用唯讀結構
public readonly struct Money
{
    public decimal Amount { get; }
    public string Currency { get; }

    public Money(decimal amount, string currency)
    {
        Amount = amount;
        Currency = currency;
    }
}

// 錯誤做法:可變結構(會導致防禦性複製)
public struct Point  // 不是唯讀的!
{
    public int X { get; set; }  // 可變的!
    public int Y { get; set; }
}

何時該使用結構

使用結構的時機使用類別的時機
小型(通常 ≤16 位元組)較大的物件
短生命週期長生命週期
經常配置需要共用參考
需要實值語意需要身分識別語意
不可變可變狀態

偏好靜態純函式

沒有副作用的靜態方法執行速度更快且更容易測試。

// 正確做法:靜態純函式
public static class OrderCalculator
{
    public static Money CalculateTotal(IReadOnlyList<OrderItem> items)
    {
        var total = items.Sum(i => i.Price * i.Quantity);
        return new Money(total, "USD");
    }
}

// 使用方式 - 可預測、可測試
var total = OrderCalculator.CalculateTotal(items);

優點:

  • 無需 vtable 查詢(更快)
  • 無隱藏狀態
  • 更容易測試(純輸入 → 輸出)
  • 設計上即為執行緒安全
  • 強制明確的相依性
// 錯誤做法:實例方法隱藏了相依性
public class OrderCalculator
{
    private readonly ITaxService _taxService;  // 隱藏的相依性
    private readonly IDiscountService _discountService;  // 隱藏的相依性

    public Money CalculateTotal(IReadOnlyList<OrderItem> items)
    {
        // 這實際上依賴了什麼?
    }
}

// 較佳做法:透過參數明確傳遞相依性
public static class OrderCalculator
{
    public static Money CalculateTotal(
        IReadOnlyList<OrderItem> items,
        decimal taxRate,
        decimal discountPercent)
    {
        // 所有輸入都是可見的
    }
}

別走火入魔 - 當你真正需要狀態或多型時,仍應使用實例方法。


延遲列舉

除非必要,否則不要將可列舉物件具體化。避免過度使用 LINQ 鏈結。

// 錯誤做法:過早具體化
public IReadOnlyList<Order> GetActiveOrders()
{
    return _orders
        .Where(o => o.IsActive)
        .ToList()  // 已具體化!
        .OrderBy(o => o.CreatedAt)  // 另一個反覆運算
        .ToList();  // 再次具體化!
}

// 正確做法:延遲到最後才具體化
public IReadOnlyList<Order> GetActiveOrders()
{
    return _orders
        .Where(o => o.IsActive)
        .OrderBy(o => o.CreatedAt)
        .ToList();  // 單次具體化
}

// 正確做法:若呼叫端可能不需要所有項目,則回傳 IEnumerable
public IEnumerable<Order> GetActiveOrders()
{
    return _orders
        .Where(o => o.IsActive)
        .OrderBy(o => o.CreatedAt);
    // 由呼叫端決定何時具體化
}

非同步列舉

小心處理 async 與 IEnumerable:

// 錯誤做法:在 LINQ 中使用非同步 - 隱藏的配置
var results = orders
    .Select(async o => await ProcessOrderAsync(o))  // 每個項目一個 Task!
    .ToList();
await Task.WhenAll(results);

// 正確做法:使用 IAsyncEnumerable 進行串流處理
public async IAsyncEnumerable<OrderResult> ProcessOrdersAsync(
    IEnumerable<Order> orders,
    [EnumeratorCancellation] CancellationToken ct = default)
{
    foreach (var order in orders)
    {
        ct.ThrowIfCancellationRequested();
        yield return await ProcessOrderAsync(order, ct);
    }
}

// 正確做法:使用批次處理進行平行化作業
var results = await Task.WhenAll(
    orders.Select(o => ProcessOrderAsync(o)));

ValueTask 與 Task 的選擇

對於經常同步完成的熱路徑,請使用 ValueTask。對於真正的 I/O 操作,直接使用 Task 即可。

// 正確做法:針對快取/同步路徑使用 ValueTask
public ValueTask<User?> GetUserAsync(UserId id)
{
    if (_cache.TryGetValue(id, out var user))
    {
        return ValueTask.FromResult<User?>(user);  // 無配置
    }

    return new ValueTask<User?>(FetchUserAsync(id));
}

// 正確做法:針對真正的 I/O 使用 Task(更簡單,無陷阱)
public Task<Order> CreateOrderAsync(CreateOrderCommand cmd)
{
    // 這個一定會存取資料庫
    return _repository.CreateAsync(cmd);
}

ValueTask 規則:

  • 絕不要對同一個 ValueTask 進行多次等候
  • 完成前絕不要使用 .Result 或 .GetAwaiter().GetResult()
  • 如有疑慮,請使用 Task

針對位元組使用 Span 與 Memory

在低階操作中,使用 Span<T> 和 Memory<T> 來取代 byte[]。

// 正確做法:同步操作接受 Span
public static int ParseInt(ReadOnlySpan<char> text)
{
    return int.Parse(text);
}

// 正確做法:非同步操作接受 Memory
public async Task WriteAsync(ReadOnlyMemory<byte> data)
{
    await _stream.WriteAsync(data);
}

// 錯誤做法:強制進行陣列配置
public static int ParseInt(string text)  // 字串已被配置
{
    return int.Parse(text);
}

常見的 Span 模式

// 不經配置進行切割
ReadOnlySpan<char> span = "Hello, World!".AsSpan();
var hello = span[..5];  // 無配置

// 為小型緩衝區使用堆疊配置
Span<byte> buffer = stackalloc byte[256];

// 為較大緩衝區使用 ArrayPool
var buffer = ArrayPool<byte>.Shared.Rent(4096);
try
{
    // 使用 buffer...
}
finally
{
    ArrayPool<byte>.Shared.Return(buffer);
}

集合回傳型別

從 API 回傳不可變集合

// 正確做法:回傳不可變集合
public IReadOnlyList<Order> GetOrders()
{
    return _orders.ToList();  // 呼叫端無法修改內部狀態
}

// 正確做法:靜態資料使用凍結集合(.NET 8+)
private static readonly FrozenDictionary<string, Handler> _handlers =
    new Dictionary<string, Handler>
    {
        ["create"] = new CreateHandler(),
        ["update"] = new UpdateHandler(),
    }.ToFrozenDictionary();

// 錯誤做法:回傳可變集合
public List<Order> GetOrders()
{
    return _orders;  // 呼叫端可以修改!
}

內部可變是沒問題的

public IReadOnlyList<OrderItem> BuildOrderItems(Cart cart)
{
    var items = new List<OrderItem>();  // 內部是可變的

    foreach (var cartItem in cart.Items)
    {
        items.Add(CreateOrderItem(cartItem));
    }

    return items;  // 以 IReadOnlyList 回傳
}

集合指南

情境回傳型別
API 邊界IReadOnlyList<T>, IReadOnlyCollection<T>
靜態查詢資料FrozenDictionary<K,V>, FrozenSet<T>
內部建構過程List<T>,然後以唯讀形式回傳
單一項目或無項目T? (可為 Null)
零或多個,可延遲IEnumerable<T>

快速參考

模式優點
sealed class去虛擬化、API 意圖清晰
readonly record struct無防禦性複製、實值語意
靜態純函式無 vtable、可測試、執行緒安全
延遲 .ToList()單次具體化
熱路徑使用 ValueTask避免 Task 配置
位元組使用 Span<T>堆疊配置、無複製
IReadOnlyList<T> 回傳不可變的 API 合約
FrozenDictionary靜態資料最快的查詢方式

反模式

// 錯誤做法:無理由的未密封類別
public class OrderService { }  // 請密封它!

// 錯誤做法:可變結構
public struct Point { public int X; public int Y; }  // 請設為唯讀

// 錯誤做法:可以為靜態的實例方法
public int Add(int a, int b) => a + b;  // 請設為靜態

// 錯誤做法:多次呼叫 ToList()
items.Where(...).ToList().OrderBy(...).ToList();  // 應在結尾呼叫一次 ToList

// 錯誤做法:從公開 API 回傳 List<T>
public List<Order> GetOrders();  // 應回傳 IReadOnlyList<T>

// 錯誤做法:對總是非同步的操作使用 ValueTask
public ValueTask<Order> CreateOrderAsync();  // 請直接使用 Task

資源

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

akka-hosting-actor-patterns

Patterns for building entity actors with Akka.Hosting - GenericChildPerEntityParent, message extractors, cluster sharding abstraction, akka-reminders, and ITimeProvider. Supports both local testing and clustered production modes.

akka-net-aspire-configuration

Configure Akka.NET with .NET Aspire for local development and production deployments. Covers actor system setup, clustering, persistence, Akka.Management integration, and Aspire orchestration patterns.

akka-net-best-practices

Critical Akka.NET best practices including EventStream vs DistributedPubSub, supervision strategies, error handling, Props vs DependencyResolver, work distribution patterns, and cluster/local mode abstractions for testability.

akka-net-management

Akka.Management for cluster bootstrapping, service discovery (Kubernetes, Azure, Config), health checks, and dynamic cluster formation without static seed nodes.

akka-net-testing-patterns

Write unit and integration tests for Akka.NET actors using modern Akka.Hosting.TestKit patterns. Covers dependency injection, TestProbes, persistence testing, and actor interaction verification. Includes guidance on when to use traditional TestKit.

api-design

Design stable, compatible public APIs using extend-only design principles. Manage API compatibility, wire compatibility, and versioning for NuGet packages and distributed systems.

aspire-configuration

Configure Aspire AppHost to emit explicit app config via environment variables; keep app code free of Aspire clients and service discovery.

aspire-integration-testing

Write integration tests using .NET Aspire

aspire-service-defaults

Create a shared ServiceDefaults project for Aspire applications. Centralizes OpenTelemetry, health checks, resilience, and service discovery configuration across all services.

crap-analysis

Analyze code coverage and CRAP (Change Risk Anti-Patterns) scores to identify high-risk code. Use OpenCover format with ReportGenerator for Risk Hotspots showing cyclomatic complexity and untested code paths.

csharp-concurrency-patterns

Choosing the right concurrency abstraction in .NET - from async/await for I/O to Channels for producer/consumer to Akka.NET for stateful entity management. Avoid locks and manual synchronization unless absolutely necessary.

database-performance

Database access patterns for performance. Separate read/write models, avoid N+1 queries, use AsNoTracking, apply row limits, and never do application-side joins. Works with EF Core and Dapper.

dependency-injection-patterns

Organize DI registrations using IServiceCollection extension methods. Group related services into composable Add* methods for clean Program.cs and reusable configuration in tests.

dotnet-devcert-trust

Diagnose and fix .NET HTTPS dev certificate trust issues on Linux. Covers the full certificate lifecycle from generation to system CA bundle inclusion, with distro-specific guidance for Ubuntu, Fedora, Arch, and WSL2.

dotnet-local-tools

Managing local .NET tools with dotnet-tools.json for consistent tooling across development environments and CI/CD pipelines.

dotnet-project-structure

Modern .NET project structure including .slnx solution format, Directory.Build.props, central package management, SourceLink, version management with RELEASE_NOTES.md, and SDK pinning with global.json.

dotnet-slopwatch

Use Slopwatch to detect LLM reward hacking in .NET code changes. Run after every code modification to catch disabled tests, suppressed warnings, empty catch blocks, and other shortcuts that mask real problems.

efcore-patterns

Entity Framework Core best practices including NoTracking by default, query splitting for navigation collections, migration management, dedicated migration services, and common pitfalls to avoid.

ilspy-decompile

Understand implementation details of .NET code by decompiling assemblies. Use when you want to see how a .NET API works internally, inspect NuGet package source, view framework implementation, or understand compiled .NET binaries.

mailpit-integration

Test email sending locally using Mailpit with .NET Aspire. Captures all outgoing emails without sending them. View rendered HTML, inspect headers, and verify delivery in integration tests.

相關技能