Logotipo de Type Design Performance

Type Design Performance

Comunidad
wshaddix
type-design-performance

Diseña tipos .NET para mejorar el rendimiento. Abarca los criterios para elegir entre struct y class, el uso de sealed de forma predeterminada, readonly structs, la elección entre ref struct y Span/Memory, FrozenDictionary, ValueTask y los tipos de colección que se devuelven. Úsalo al diseñar nuevos tipos y API, revisar código para detectar problemas de rendimiento, elegir entre class, struct y record, o trabajar con colecciones y enumerables.

Add to TypingMind

Descripción general

Editorwshaddix
Repositoriodotnet-skills
Nombre de la habilidadtype-design-performance
Estrellas
79
Forks
13
Archivos incluidos
Solo instrucciones
Enlaces
  • Instrucciones en Markdown

    Un archivo SKILL.md que el modelo carga cuando lo necesita, de modo que solo consume tokens cuando la petición encaja con la habilidad.

  • Funciona con cualquier LLM

    Las habilidades de IA están en Markdown, no en código específico de un proveedor, por lo que funcionan con GPT, Claude, Gemini, Grok o un modelo local.

  • Todo en las instrucciones

    Todo lo que necesita el modelo está en las instrucciones: no hay archivos adicionales que sincronizar.

  • Código abierto

    Publicada por wshaddix en GitHub. Revisa el contenido original antes de instalarla.

Instalación

Instala la habilidad de IA Type Design Performance en TypingMind para usarla con cualquier LLM, o añádela a otro agente que lea SKILL.md.

1

Instalar en TypingMind

TypingMind instala una habilidad directamente desde su carpeta de GitHub: lee SKILL.md, empaqueta los archivos de recursos y guarda el resultado localmente.

  1. Abre la aplicación y ve a Plugins → Habilidades.
  2. Elige «Instalar desde GitHub».
  3. Pega la URL de la carpeta de la habilidad que se muestra a continuación y confirma.
    https://github.com/wshaddix/dotnet-skills/tree/master/skills/csharp-type-design-performance
  4. Activa la habilidad en cada chat en el que quieras tenerla disponible.
Plugins → Habilidades → Añadir habilidad → URL de GitHub; después, pega la URL de la carpeta y pulsa Continuar.
2

Instalar en otro agente

Cualquier agente que lea el formato Agent Skills puede usar esta habilidad: copia la carpeta en el directorio de habilidades de ese agente.

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
Reinicia Claude Code después de copiarla para que detecte la nueva habilidad.

Úsala en TypingMind

Activa Type Design Performance en cualquier chat de TypingMind y el modelo se encargará del resto. Su nombre y descripción se incluyen en el prompt del sistema y, en cuanto una petición encaja con la habilidad, el modelo carga las instrucciones completas por sí solo. No tienes que invocarla manualmente y no consume tokens hasta que se utiliza.

El modelo carga Type Design Performance automáticamente en cuanto una petición es relevante para esa habilidad.

Funciona con cualquier modelo de IA

Las habilidades de IA son instrucciones en Markdown, no código específico de un proveedor, por lo que Type Design Performance no está vinculada al modelo para el que se creó. Instálala una sola vez en TypingMind y úsala con GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama o un modelo local que ejecutes tú, todo con tus propias claves API.

  • Se carga solo cuando se necesita

    El prompt del sistema solo incluye el nombre y la descripción. Las instrucciones se cargan con la primera petición que encaja con la habilidad, por lo que una habilidad que no se usa no supone ningún coste.

  • Cambia de modelo durante el chat

    Como la habilidad contiene instrucciones y no código, cambiar de modelo no impide que funcione: el nuevo modelo lee el mismo archivo SKILL.md.

Instrucciones de la habilidad

Este es el contenido de SKILL.md que carga el modelo. Léelo antes de instalar la habilidad: contiene instrucciones que tu modelo seguirá.

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

Preguntas frecuentes

¿Qué hace la habilidad de IA Type Design Performance?

Diseña tipos .NET para mejorar el rendimiento. Abarca los criterios para elegir entre struct y class, el uso de sealed de forma predeterminada, readonly structs, la elección entre ref struct y Span/Memory, FrozenDictionary, ValueTask y los tipos de colección que se devuelven. Úsalo al diseñar nuevos tipos y API, revisar código para detectar problemas de rendimiento, elegir entre class, struct y record, o trabajar con colecciones y enumerables.

¿Por qué usar Type Design Performance en TypingMind?

Porque la instalas una vez y la usas con cualquier modelo. Type Design Performance está escrita en Markdown, no en código específico de un proveedor, por lo que la misma habilidad funciona con GPT-5, Claude, Gemini, Grok o un modelo local, y puedes cambiar de modelo en mitad del chat sin que deje de funcionar. TypingMind utiliza tus propias claves API, de modo que pagas directamente a los proveedores en lugar de pagar una suscripción por puesto, y tus habilidades y chats permanecen en tu propio almacenamiento.

¿Cómo instalo Type Design Performance en TypingMind?

Abre Plugins → Habilidades → Instalar desde GitHub en TypingMind y pega https://github.com/wshaddix/dotnet-skills/tree/master/skills/csharp-type-design-performance. TypingMind lee el archivo SKILL.md de esa carpeta e instala su contenido como una habilidad que puedes activar en cada chat.

¿Qué modelos de IA pueden usar Type Design Performance?

Cualquier modelo que conectes en TypingMind. Las habilidades de IA son instrucciones en Markdown, no código específico de un proveedor, por lo que GPT, Claude, Gemini, Grok y los modelos locales pueden cargar esta habilidad cuando una solicitud se corresponda con ella.

¿Con cuántos modelos de IA puedo usar Type Design Performance?

Con tantos como quieras. Siempre que un modelo admita habilidades, puedes usar Type Design Performance con él: GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama y muchos más, todos en TypingMind con tus propias claves API.

¿Es gratuita la habilidad de IA Type Design Performance?

wshaddix la ha publicado en GitHub. Consulta el repositorio para conocer las condiciones de la licencia. Solo pagas a tu proveedor de IA por los tokens que utilizas.

¿Qué son las habilidades de IA?

Una habilidad de IA es un conjunto de instrucciones reutilizables que enseña a un modelo de IA a realizar una tarea concreta. Sigue el formato abierto Agent Skills: un archivo SKILL.md con un nombre y una descripción, además de los scripts, plantillas o archivos de referencia que pueda necesitar el modelo. El modelo solo lee las instrucciones cuando tu solicitud se corresponde con la habilidad, por lo que una habilidad instalada no supone ningún coste hasta que se utiliza.

¿En qué se diferencian las habilidades de IA de los plugins o los servidores MCP?

Un plugin o un servidor MCP proporciona al modelo nuevas herramientas que puede invocar: código que se ejecuta en algún lugar y devuelve un resultado. En cambio, una habilidad de IA aporta conocimientos y procedimientos al modelo: cómo abordar una tarea, qué pasos seguir y qué se considera un buen resultado. Las habilidades son instrucciones en Markdown, por lo que no necesitan servidor, clave API ni entorno de ejecución, y funcionan con cualquier modelo.

Ver el directorio

Crea ya tu propio espacio de trabajo con IA

Suscríbete a nuestro boletín para recibir avisos sobre nuevas funciones y próximos sorteos 👇