Type Design Performance logo

Type Design Performance

Community
wshaddix
type-design-performance

Design .NET types for performance. Covers struct vs class decision matrix, sealed by default, readonly structs, ref struct and Span/Memory selection, FrozenDictionary, ValueTask, and collection return types. Use when designing new types and APIs, reviewing code for performance issues, choosing between class, struct, and record, or working with collections and enumerables.

Overview

Publisherwshaddix
Repositorydotnet-skills
Skill nametype-design-performance
Stars
79
Forks
13
Bundled files
Instructions only
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • Self-contained

    Everything the model needs lives in the instructions — no extra files to sync.

  • Open source

    Published by wshaddix on GitHub. Read the source before you install it.

Installation

Install the Type Design Performance AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

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
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Type Design Performance in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads Type Design Performance on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so Type Design Performance is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

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

Frequently asked questions

What does the Type Design Performance AI skill do?

Design .NET types for performance. Covers struct vs class decision matrix, sealed by default, readonly structs, ref struct and Span/Memory selection, FrozenDictionary, ValueTask, and collection return types. Use when designing new types and APIs, reviewing code for performance issues, choosing between class, struct, and record, or working with collections and enumerables.

Why use Type Design Performance on TypingMind?

Because you install it once and use it with any model. Type Design Performance is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install Type Design Performance in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/wshaddix/dotnet-skills/tree/master/skills/csharp-type-design-performance. TypingMind reads its SKILL.md and installs it as a skill you can enable per chat.

Which AI models can use Type Design Performance?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with Type Design Performance?

As many as you like. As long as a model supports skills, you can use Type Design Performance with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the Type Design Performance AI skill free?

It is published on GitHub by wshaddix. Check the repository for licensing terms. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇