Performance tips for faster C# code.
1. Use Span<T> for string operations:
1// Bad2string sub = str.Substring(1, 5); // Allocation34// Good5Span<char> span = str.AsSpan().Slice(1, 5); // No allocation
2. Use StringBuilder for loops:
1// Bad2string s = "";3for (int i = 0; i < 1000; i++)4 s += i; // 1000 allocations56// Good7var sb = new StringBuilder();8for (int i = 0; i < 1000; i++)9 sb.Append(i); // 1 allocation
3. Use struct for small types:
1// Bad2class Point { public int X, Y; } // Heap allocation34// Good5struct Point { public int X, Y; } // Stack allocation
4. Use object pooling:
1var pool = ArrayPool<byte>.Shared;2byte[] buffer = pool.Rent(1024);3try { /* use buffer */ }4finally { pool.Return(buffer); }
5. Use frozen collections:
1var frozen = dict.ToFrozenDictionary(); // Optimized reads