Token导航 LogoToken导航TokenDH.com
开发需要联网github未标认证来源可访问许可证需确认审计通过

type-design-performance型式设计性能

Agent Skill

用于辅助界面设计、视觉规范、排版、配色、布局和交互体验优化。它适合让 Agent 根据产品场景整理页面结构、生成 UI 方案、检查视觉一致性或改进组件层级。使用时需要结合现有品牌、设计系统和用户任务,不应只堆装饰元素;涉及真实页面改动时,应通过截图或浏览器预览检查文本溢出、对齐和响应式表现。

总安装

343

周安装

14

GitHub Stars

15

下载量

111
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:type-design-performance(型式设计性能)
来源仓库:https://github.com/wshaddix/dotnet-skills
仓库路径:skills/type-design-performance
安装命令:
npx skills add https://github.com/wshaddix/dotnet-skills --skill type-design-performance
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/wshaddix/dotnet-skills --skill type-design-performance

简介

type-design-performance 辅助界面设计、视觉规范和交互体验优化。

  • 适合整理页面结构、生成 UI 方案或改进组件层级。
  • 通过 npx skills add 命令从指定 GitHub 仓库安装并使用。
  • 涉及真实页面改动时,应通过截图或浏览器预览检查表现。
  • 适用宿主包括 Codex、Claude、Cursor、Gemini CLI,接入前应确认版本、权限和运行环境要求。

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
// 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

// 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!
}
// 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
// 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.

// 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.

// 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

// 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.

// 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

// 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

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

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

// 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

// 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

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

39.46%
按下载量换算44

Claude

28.25%
按下载量换算31

Cursor

17.9%
按下载量换算20

Gemini CLI

10.6%
按下载量换算12

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills