← ClaudeAtlas

optimizing-memory-allocationlisted

Implements Zero Allocation patterns using Span, ArrayPool, and ObjectPool for memory efficiency in .NET. Use when reducing GC pressure or optimizing high-performance memory operations.
christian289/dotnet-with-claudecode · ★ 41 · Data & Documents · score 73
Install: claude install-skill christian289/dotnet-with-claudecode
# .NET Memory Efficiency, Zero Allocation A guide for APIs that minimize GC pressure and enable high-performance memory management. **Quick Reference:** See [QUICKREF.md](QUICKREF.md) for essential patterns at a glance. ## 1. Core Concepts - .NET CLR GC Heap Memory Optimization - Understanding Stack allocation vs Heap allocation - Stack-only types through ref struct ## 2. Key APIs | API | Purpose | NuGet | |-----|---------|-------| | `Span<T>`, `Memory<T>` | Stack-based memory slicing | BCL | | `ArrayPool<T>.Shared` | Reduce GC pressure through array reuse | BCL | | `DefaultObjectPool<T>` | Object pooling | Microsoft.Extensions.ObjectPool | | `MemoryCache` | In-memory caching | System.Runtime.Caching | --- ## 3. Span<T>, ReadOnlySpan<T> ### 3.1 Basic Usage ```csharp // Zero Allocation when parsing strings public void ParseData(ReadOnlySpan<char> input) { // String manipulation without Heap allocation var firstPart = input.Slice(0, 10); var secondPart = input.Slice(10); } // Array slicing public void ProcessArray(int[] data) { Span<int> span = data.AsSpan(); Span<int> firstHalf = span[..^(span.Length / 2)]; Span<int> secondHalf = span[(span.Length / 2)..]; } ``` ### 3.2 String Processing Optimization ```csharp // ❌ Bad example: Substring allocates new string string part = text.Substring(0, 10); // ✅ Good example: AsSpan has no allocation ReadOnlySpan<char> part = text.AsSpan(0, 10); ``` ### 3.3 Using with stackalloc ```csharp public void