Type Design Performance 标志

Type Design Performance

社区
wshaddix
type-design-performance

面向性能设计 .NET 类型。涵盖 struct 与 class 的选择矩阵、默认密封类型、只读结构体、ref struct 与 Span/Memory 的选择、FrozenDictionary、ValueTask,以及集合返回类型。适用于设计新类型和 API、审查代码中的性能问题、在 class、struct 和 record 之间进行选择,或处理集合和可枚举对象。

Add to TypingMind

概览

发布者wshaddix
代码仓库dotnet-skills
技能名称type-design-performance
星标数
79
复刻数
13
附带文件
仅含指令
链接
  • Markdown 格式的指令

    模型按需加载 SKILL.md 文件,因此只有在请求确实与该技能匹配时才会消耗 Token。

  • 兼容任何大语言模型

    AI 技能采用纯 Markdown,而非特定提供商的代码,因此可搭配 GPT、Claude、Gemini、Grok 或本地模型使用。

  • 指令自成一体

    模型所需的一切都包含在指令中,无需同步额外文件。

  • 开源

    由 wshaddix 发布于 GitHub。请在安装前查看技能的源文件。

安装

在 TypingMind 中安装 Type Design Performance AI 技能,即可搭配任意大语言模型使用;也可以将其放入其他支持读取 SKILL.md 的智能体中。

1

安装到 TypingMind

TypingMind 可直接从 GitHub 文件夹安装技能:读取 SKILL.md,打包资源文件,并将结果保存在本地。

  1. 打开应用,前往“插件 → 技能”。
  2. 选择“从 GitHub 安装”。
  3. 粘贴下方的技能文件夹 URL 并确认。
    https://github.com/wshaddix/dotnet-skills/tree/master/skills/csharp-type-design-performance
  4. 请在每个需要使用该技能的聊天中启用它。
依次选择“插件 → 技能 → 添加技能 → 从 GitHub URL 导入”,然后粘贴文件夹 URL 并点击“继续”。
2

安装到其他智能体

任何支持 Agent Skills 格式的智能体都可以使用此技能,只需将文件夹复制到该智能体的技能目录中。

Claude Code — .claude/skills
git clone --depth 1 https://github.com/wshaddix/dotnet-skills.git /tmp/dotnet-skills
mkdir -p .claude/skills
cp -r /tmp/dotnet-skills/skills/csharp-type-design-performance .claude/skills/type-design-performance
复制后,请重启 Claude Code,以加载新技能。

在 TypingMind 中使用此技能

在任意 TypingMind 聊天中启用 Type Design Performance,后续即可交由模型处理。技能的名称和描述会放在系统提示词中,一旦请求匹配,模型就会自动加载完整指令,无需您手动调用,且在实际使用前不会消耗 Token。

一旦请求与技能匹配,模型就会自动加载 Type Design Performance。

兼容任何 AI 模型

AI 技能是纯 Markdown 指令,而非特定提供商的代码,因此 Type Design Performance 不局限于最初适配的模型。只需在 TypingMind 中安装一次,即可搭配 GPT-5、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 或您自行运行的本地模型使用,全程使用您自己的 API 密钥。

  • 仅在需要时加载

    系统提示词中仅包含技能名称和描述。首次遇到匹配的请求时才会加载完整指令,因此技能未使用时,这些指令不会消耗 Token。

  • 在聊天中切换模型

    技能是指令而非代码,因此切换模型不会导致技能失效,新模型会读取同一个 SKILL.md。

技能指令

这是模型会加载的 SKILL.md 内容。请在安装前阅读,因为技能就是模型将遵循的指令。

Type Design for Performance

When to Use This Skill

Use this skill when:

  • Designing new types and APIs
  • Reviewing code for performance issues
  • Choosing between class, struct, and record
  • Working with collections and enumerables

Core Principles

  1. Seal your types - Unless explicitly designed for inheritance
  2. Prefer readonly structs - For small, immutable value types
  3. Prefer static pure functions - Better performance and testability
  4. Defer enumeration - Don't materialize until you need to
  5. Return immutable collections - From API boundaries

Struct vs Class Decision Matrix

Choosing between struct and class at design time has cascading effects on allocation, GC pressure, and API shape.

Decision Criteria

CriterionFavors structFavors class
SizeSmall (<= 16 bytes ideal, <= 64 bytes acceptable)Large or variable size
LifetimeShort-lived, method-scopedLong-lived, shared across scopes
IdentityValue equality (two instances with same data are equal)Reference identity matters
MutabilityImmutable (readonly struct)Mutable or complex state transitions
InheritanceNot neededRequires polymorphism or base class
Nullable semanticsdefault is a valid zero stateNeeds explicit null to signal absence
Collection usageStored in arrays/spans (contiguous memory)Stored via references (indirection)

Size Guidelines

<= 16 bytes:  Ideal struct -- fits in two registers, passed efficiently
17-64 bytes:  Acceptable struct -- measure copy cost vs allocation cost
> 64 bytes:   Prefer class -- copying cost outweighs allocation avoidance

Common Types and Their Correct Design

TypeCorrect ChoiceWhy
Point2D (8 bytes: two floats)readonly structSmall, immutable, value semantics
Money (16 bytes: decimal + currency)readonly structSmall, immutable, value equality
DateRange (16 bytes: two DateOnly)readonly structSmall, immutable, value semantics
Matrix4x4 (64 bytes: 16 floats)struct (with in parameters)Performance-critical math
CustomerDto (variable: strings, lists)class or recordContains references, variable size
HttpRequest contextclassLong-lived, shared across middleware

Sealed by Default

Why Seal Library Types

For library types (code consumed by other assemblies), seal classes by default:

  1. JIT devirtualization -- sealed classes enable the JIT to replace virtual calls with direct calls, enabling inlining
  2. Simpler contracts -- unsealed classes imply a promise to support inheritance
  3. Fewer breaking changes -- sealing a class later is a binary-breaking change
csharp
// GOOD -- sealed by default for library types
public sealed class WidgetService
{
    public Widget GetWidget(int id) => new(id, "Default");
}

// Only unseal when inheritance is an intentional design decision
public abstract class WidgetValidatorBase
{
    public abstract bool Validate(Widget widget);
    protected virtual void OnValidationComplete(Widget widget) { }
}

When NOT to Seal

ScenarioReason
Abstract base classesInheritance is the purpose
Framework extensibility pointsConsumers need to subclass
Test doubles in non-mockable designsMocking frameworks need to subclass
Application-internal classesSealing adds no value

Readonly Structs

Mark structs readonly when all fields are immutable. This eliminates defensive copies the JIT creates when accessing structs through in parameters or readonly fields.

The Defensive Copy Problem

csharp
// NON-readonly struct -- JIT must defensively copy on every method call
public struct MutablePoint
{
    public double X;
    public double Y;
    public double Length() => Math.Sqrt(X * X + Y * Y);
}

public double GetLength(in MutablePoint point)
{
    return point.Length(); // Hidden copy here!
}
csharp
// GOOD -- readonly struct: JIT knows no mutation is possible
public readonly struct ImmutablePoint
{
    public double X { get; }
    public double Y { get; }

    public ImmutablePoint(double x, double y) => (X, Y) = (x, y);

    public double Length() => Math.Sqrt(X * X + Y * Y);
}

public double GetLength(in ImmutablePoint point)
{
    return point.Length(); // No copy, direct call
}

Readonly Struct Checklist

  • All fields are readonly or { get; } / { get; init; } properties
  • No methods mutate state
  • Constructor initializes all fields
  • Consider IEquatable<T> for value comparison without boxing

Record Types for Data Transfer

record class vs record struct

Characteristicrecord classrecord struct
AllocationHeapStack (or inline in arrays)
EqualityReference type with value equalityValue type with value equality
with expressionCreates new heap objectCreates new stack copy
Nullablenull represents absencedefault represents empty state
SizeReference (8 bytes on x64) + heapFull size on stack
csharp
// record class -- heap allocated, good for DTOs
public record CustomerDto(string Name, string Email, DateOnly JoinDate);

// readonly record struct -- stack allocated, good for small value objects
public readonly record struct Money(decimal Amount, string Currency);

Prefer Static Pure Functions

Static methods with no side effects are faster and more testable.

csharp
// DO: Static pure function
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");
    }
}

// Usage - predictable, testable
var total = OrderCalculator.CalculateTotal(items);

Benefits:

  • No vtable lookup (faster)
  • No hidden state
  • Easier to test (pure input → output)
  • Thread-safe by design
  • Forces explicit dependencies

Defer Enumeration

Don't materialize enumerables until necessary. Avoid excessive LINQ chains.

csharp
// BAD: Premature materialization
public IReadOnlyList<Order> GetActiveOrders()
{
    return _orders
        .Where(o => o.IsActive)
        .ToList()  // Materialized!
        .OrderBy(o => o.CreatedAt)  // Another iteration
        .ToList();  // Materialized again!
}

// GOOD: Defer until the end
public IReadOnlyList<Order> GetActiveOrders()
{
    return _orders
        .Where(o => o.IsActive)
        .OrderBy(o => o.CreatedAt)
        .ToList();  // Single materialization
}

// GOOD: Return IEnumerable if caller might not need all items
public IEnumerable<Order> GetActiveOrders()
{
    return _orders
        .Where(o => o.IsActive)
        .OrderBy(o => o.CreatedAt);
}

Async Enumeration

csharp
// GOOD: Use IAsyncEnumerable for streaming
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);
    }
}

// GOOD: Batch processing for parallelism
var results = await Task.WhenAll(
    orders.Select(o => ProcessOrderAsync(o)));

ValueTask vs Task

Use ValueTask for hot paths that often complete synchronously. For real I/O, just use Task.

csharp
// DO: ValueTask for cached/synchronous paths
public ValueTask<User?> GetUserAsync(UserId id)
{
    if (_cache.TryGetValue(id, out var user))
    {
        return ValueTask.FromResult<User?>(user);  // No allocation
    }

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

// DO: Task for real I/O (simpler, no footguns)
public Task<Order> CreateOrderAsync(CreateOrderCommand cmd)
{
    return _repository.CreateAsync(cmd);
}

ValueTask rules:

  • Never await a ValueTask more than once
  • Never use .Result or .GetAwaiter().GetResult() before completion
  • If in doubt, use Task

ref struct and Span/Memory Selection

ref struct Constraints

ref struct types are stack-only: they cannot be boxed, stored in fields of non-ref-struct types, or used in async methods.

Span vs Memory Decision

CriterionUse Span<T>Use Memory<T>
Synchronous methodYesYes (but Span is lower overhead)
Async methodNo (ref struct)Yes
Store in field/collectionNo (ref struct)Yes
Pass to callback/delegateNoYes
Slice without allocationYesYes
Wrap stackalloc bufferYesNo

Selection Flowchart

Will the buffer be used in an async method or stored in a field?
  YES -> Use Memory<T> (convert to Span<T> with .Span for synchronous processing)
  NO  -> Do you need to wrap a stackalloc buffer?
           YES -> Use Span<T>
           NO  -> Prefer Span<T> for lowest overhead

Practical Pattern

csharp
// Public API uses Memory<T> for maximum flexibility
public async Task<int> ProcessAsync(ReadOnlyMemory<byte> data,
    CancellationToken ct = default)
{
    await _stream.WriteAsync(data, ct);
    return CountNonZero(data.Span);
}

// Internal hot-path method uses Span<T> for zero overhead
private static int CountNonZero(ReadOnlySpan<byte> data)
{
    var count = 0;
    foreach (var b in data)
    {
        if (b != 0) count++;
    }
    return count;
}

Common Span Patterns

csharp
// Slice without allocation
ReadOnlySpan<char> span = "Hello, World!".AsSpan();
var hello = span[..5];  // No allocation

// Stack allocation for small buffers
Span<byte> buffer = stackalloc byte[256];

// Use ArrayPool for larger buffers
var buffer = ArrayPool<byte>.Shared.Rent(4096);
try
{
    // Use buffer...
}
finally
{
    ArrayPool<byte>.Shared.Return(buffer);
}

Collection Type Selection

Decision Matrix

ScenarioRecommended TypeRationale
Build once, read manyFrozenDictionary<K,V> / FrozenSet<T>Optimized read layout (.NET 8+)
Build once, read many (pre-.NET 8)ImmutableDictionary<K,V>Thread-safe, immutable
Concurrent read/writeConcurrentDictionary<K,V>Thread-safe without external locking
Frequent modificationsDictionary<K,V>Lowest per-operation overhead
Ordered dataSortedDictionary<K,V>O(log n) lookup with sorted enumeration
Return from public APIIReadOnlyList<T> / IReadOnlyDictionary<K,V>Immutable interface
Stack-allocated small collectionSpan<T> with stackallocZero GC pressure

FrozenDictionary (.NET 8+)

FrozenDictionary<K,V> optimizes the internal layout at creation time for maximum read performance:

csharp
using System.Collections.Frozen;

private static readonly FrozenDictionary<string, int> StatusCodes =
    new Dictionary<string, int>
    {
        ["OK"] = 200,
        ["NotFound"] = 404,
        ["InternalServerError"] = 500
    }.ToFrozenDictionary(StringComparer.OrdinalIgnoreCase);

public int GetStatusCode(string name) =>
    StatusCodes.TryGetValue(name, out var code) ? code : -1;

When to use FrozenDictionary:

  • Configuration lookup tables populated at startup
  • Static mappings (enum-to-string, error codes, feature flags)
  • Any dictionary populated once and read many times

When NOT to use:

  • Data that changes at runtime
  • Small lookups (< 10 items) where optimization overhead is not recouped

Collection Return Types

csharp
// DO: Return immutable collection
public IReadOnlyList<Order> GetOrders()
{
    return _orders.ToList();
}

// DO: Use frozen collections for static data
private static readonly FrozenDictionary<string, Handler> _handlers =
    new Dictionary<string, Handler>
    {
        ["create"] = new CreateHandler(),
        ["update"] = new UpdateHandler(),
    }.ToFrozenDictionary();

// DON'T: Return mutable collection
public List<Order> GetOrders()
{
    return _orders;  // Caller can modify!
}

Quick Reference

PatternBenefit
sealed classDevirtualization, clear API
readonly record structNo defensive copies, value semantics
Static pure functionsNo vtable, testable, thread-safe
Defer .ToList()Single materialization
ValueTask for hot pathsAvoid Task allocation
Span<T> for bytesStack allocation, no copying
IReadOnlyList<T> returnImmutable API contract
FrozenDictionaryFastest lookup for static data

Anti-Patterns

csharp
// DON'T: Unsealed class without reason
public class OrderService { }  // Seal it!

// DON'T: Mutable struct
public struct Point { public int X; public int Y; }  // Make readonly

// DON'T: Instance method that could be static
public int Add(int a, int b) => a + b;  // Make static

// DON'T: Multiple ToList() calls
items.Where(...).ToList().OrderBy(...).ToList();  // One ToList at end

// DON'T: Return List<T> from public API
public List<Order> GetOrders();  // Return IReadOnlyList<T>

// DON'T: ValueTask for always-async operations
public ValueTask<Order> CreateOrderAsync();  // Just use Task

// DON'T: Use `Span<T>` in async methods
public async Task ProcessAsync(Span<byte> data);  // Use Memory<T>

// DON'T: Use `FrozenDictionary` for mutable data
// It has no add/remove APIs

Agent Gotchas

  1. Do not default to class for every type -- evaluate the struct vs class decision matrix.
  2. Do not create non-readonly structs -- mutable structs cause subtle bugs.
  3. Do not use Span<T> in async methods -- use Memory<T> for async code.
  4. Do not use FrozenDictionary for mutable data -- it has no add/remove APIs.
  5. Do not seal abstract classes or classes designed as extension points.
  6. Do not make large structs (> 64 bytes) without measuring -- benchmark copy cost.
  7. Do not use Dictionary<K,V> for static lookup tables in hot paths -- use FrozenDictionary.
  8. Do not forget in parameter for large readonly structs -- without in, the struct is copied.

Resources

常见问题

Type Design Performance AI 技能有什么作用?

面向性能设计 .NET 类型。涵盖 struct 与 class 的选择矩阵、默认密封类型、只读结构体、ref struct 与 Span/Memory 的选择、FrozenDictionary、ValueTask,以及集合返回类型。适用于设计新类型和 API、审查代码中的性能问题、在 class、struct 和 record 之间进行选择,或处理集合和可枚举对象。

为什么在 TypingMind 中使用 Type Design Performance?

因为您只需安装一次,就能搭配任何模型使用。Type Design Performance 采用纯 Markdown 格式,而非特定提供商专用的代码,因此同一技能可用于 GPT-5、Claude、Gemini、Grok 或本地模型。您甚至可以在聊天中途切换模型,而不会影响技能的正常使用。TypingMind 使用您自己的 API 密钥,因此您直接向提供商付费,而不是按席位订阅;您的技能和聊天记录也都保留在您自己的存储空间中。

如何在 TypingMind 中安装 Type Design Performance?

在 TypingMind 中打开“插件 → 技能 → 从 GitHub 安装”,然后粘贴 https://github.com/wshaddix/dotnet-skills/tree/master/skills/csharp-type-design-performance。TypingMind 会读取其中的 SKILL.md,并将其安装为技能,供您在各个聊天中按需启用。

哪些 AI 模型可以使用 Type Design Performance?

您在 TypingMind 中连接的任何模型都可以。AI 技能采用纯 Markdown 指令,而非特定提供商专用的代码,因此 GPT、Claude、Gemini、Grok 和本地模型都能在请求匹配时加载此技能。

Type Design Performance 可以搭配多少个 AI 模型使用?

数量不限。只要模型支持技能,您就可以将它与 Type Design Performance 搭配使用。GPT、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 等模型都可以通过您自己的 API 密钥接入 TypingMind。

Type Design Performance AI 技能免费吗?

wshaddix 已在 GitHub 上发布了该技能。请查看代码仓库了解许可条款。您只需向自己的 AI 提供商支付所用 Token 的费用。

什么是 AI 技能?

AI 技能是一组可复用的指令,用于教会 AI 模型完成某项特定任务。它遵循开放的 Agent Skills 格式:包含名称和描述的 SKILL.md 文件,以及模型可能需要的脚本、模板或参考文件。模型仅在您的请求与技能匹配时才会读取这些指令,因此已安装的技能在使用前不会产生任何费用。

AI 技能与插件或 MCP 服务器有何不同?

插件或 MCP 服务器为模型提供可调用的新工具,也就是在某处运行并返回结果的代码。AI 技能则为模型提供知识和流程:如何处理任务、遵循哪些步骤,以及怎样的输出才算优质。技能采用纯 Markdown 格式,因此不需要服务器、API 密钥或运行时环境,并且适用于任何模型。

查看全部

立即创建您自己的 AI 工作区

订阅我们的电子简报,获取新功能和后续赠奖活动的通知 👇