Community编程与开发github.com

类型设计性能优化

设计高性能的.NET类型。密封类、使用只读结构体、优先使用静态纯函数、避免过早枚举,并选择合适的集合类型。

类型设计性能优化 是什么?

这个技能指导开发者如何设计高性能的.NET类型,涵盖类、结构体、记录、集合和异步模式。它提供了具体的C#代码示例,展示如何通过密封类启用JIT去虚拟化、使用只读结构体避免防御性拷贝、优先使用静态纯函数提升可测试性和性能、推迟枚举以减少不必要的内存分配,以及从API边界返回不可变集合来保护内部状态。技能还对比了 ValueTask 和 Task 的适用场景,介绍了 Span<T> 和 Memory<T> 用于零分配字节操作,并提供了可冻结集合(FrozenDictionary/FrozenSet)用于静态数据。该技能适用于Claude Code、Cursor、Codex等支持C#开发的AI Agent工具,帮助开发者编写更高效、更可维护的代码。

兼容平台~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时
  • 审查代码中的性能问题
  • 选择使用类、结构体还是记录时
  • 处理集合和可枚举对象时

核心原则

  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) { }  // 虚方法 = 更慢
}

好处:

  • 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);
    // 由调用方决定何时具体化
}

异步枚举

小心使用异步和IEnumerable:

// 糟糕:LINQ中的异步 - 隐藏的分配
var results = orders
    .Select(async o => await ProcessOrderAsync(o))  // 每个项目一个Task!
    .ToList();
avait 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
{
    // 使用缓冲区...
}
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?(可为空)
零个或多个,延迟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.

相关技能