0 day streak
Code library

Code worth reading.

Hand-picked snippets across TypeScript, Python, Rust, Go, and more — each one comes with a line-by-line breakdown so you can read it like the people who wrote it.

3495 snippets · 10 languages
▶ Start learning
C# · ExpertSnippet

SIMD Vectorization with Vector<T>

Single Instruction, Multiple Data (SIMD) allows a single CPU instruction to process multiple data points simultaneously. Vector<T> in C# enables hardware-accelerated parallel processing on arrays, significantly boosting performance for mathematical and data-heavy algorithms.

snippet.cs
csharp
1
2
3
4
5
6
7
8
public void VectorAdd(int[] a, int[] b, int[] result) {
int vSize = Vector<int>.Count;
for (int i = 0; i <= a.Length - vSize; i += vSize) {
var v1 = new Vector<int>(a, i);
var v2 = new Vector<int>(b, i);
(v1 + v2).CopyTo(result, i);
}
}
PerformanceArrays & ListsMemory Management
C# · ExpertSnippet

Advanced Interop with Unsafe Pointers

The 'unsafe' keyword allows C# to perform pointer arithmetic, similar to C++. Using 'fixed' pins the managed object in memory, preventing the Garbage Collector from moving it while you directly manipulate its memory addresses for maximum throughput in low-level scenarios.

snippet.cs
csharp
1
2
3
4
5
6
7
8
9
public unsafe void FastCopy(byte[] src, byte[] dest) {
fixed (byte* pSrc = src, pDest = dest) {
byte* ps = pSrc;
byte* pd = pDest;
for (int i = 0; i < src.Length; i++) {
*pd++ = *ps++;
}
}
}
Memory ManagementPerformanceSyntax
C# · ExpertSnippet

Memory Efficiency with Span<T> and Stackalloc

Span<T> provides a type-safe and memory-safe representation of a contiguous region of arbitrary memory. By combining it with stackalloc, you can perform high-performance buffer operations entirely on the stack, bypassing the Garbage Collector and reducing memory pressure.

snippet.cs
csharp
1
2
3
4
5
public void ProcessData(ReadOnlySpan<byte> data) {
Span<byte> buffer = stackalloc byte[128];
data.Slice(0, 64).CopyTo(buffer);
// Perform operations without heap allocation
}
Memory ManagementPerformanceBest Practices
C# · ExpertSnippet

Dynamic Query Compilation via Expression Trees

Expression trees represent code in a tree-like data structure, where each node is an expression. Expert developers use this for metaprogramming, such as building dynamic LINQ providers or compiling highly optimized logic at runtime that would otherwise require slow reflection.

snippet.cs
csharp
1
2
3
4
5
6
ParameterExpression param = Expression.Parameter(typeof(int), "x");
BinaryExpression body = Expression.GreaterThan(param, Expression.Constant(10));
Expression<Func<int, bool>> lambda = Expression.Lambda<Func<int, bool>>(body, param);
Func<int, bool> compiled = lambda.Compile();
bool result = compiled(15);
SyntaxDesign PatternsPerformance
C# · ExpertSnippet

Implementing Custom Awaiters

In C#, any type can be awaited if it follows the 'GetAwaiter' pattern. This expert-level technique allows you to create custom asynchronous primitives without relying on Task or ValueTask, reducing allocation overhead in specialized high-performance scenarios.

snippet.cs
csharp
1
2
3
4
5
6
7
8
9
public struct MyTaskAwaiter : INotifyCompletion {
public bool IsCompleted => false;
public void OnCompleted(Action continuation) => Task.Run(continuation);
public void GetResult() { }
}
public struct MyCustomTask {
public MyTaskAwaiter GetAwaiter() => new MyTaskAwaiter();
}
Async & ConcurrencyPerformanceDesign Patterns
C# · ExpertSnippet

Generic Math via Static Abstract Members

Static abstract members in interfaces allow C# to define operators and static properties within an interface. This is the foundation of 'Generic Math', enabling developers to write generic algorithms that work across all numeric types (int, float, decimal, etc.) by constraining type parameters to the INumber<T> interface.

snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
using System.Numerics;
public static class MathUtils {
public static T SumAll<T>(IEnumerable<T> values) where T : INumber<T> {
T result = T.Zero;
foreach (var value in values) {
result += value;
}
return result;
}
}
// Usage
double dSum = MathUtils.SumAll(new[] { 1.5, 2.5 });
int iSum = MathUtils.SumAll(new[] { 10, 20 });
OOPDesign Patterns
C# · ExpertSnippet

Unsafe Accessors for Zero-Overhead Private Member Access

Introduced in C# 12, Unsafe Accessors allow code to access private members of other classes without the performance penalty of Reflection. By using the [UnsafeAccessor] attribute on an extern static method, the compiler generates a direct IL reference to the private field or method, making it as fast as a public access while bypassing visibility constraints.

snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
using System.Runtime.CompilerServices;
public class DataBuffer {
private int _secretId = 42;
}
public class Accessor {
[UnsafeAccessor(UnsafeAccessorKind.Field, Name = "_secretId")]
public static extern ref int GetSecretId(DataBuffer buffer);
}
// Usage
var buffer = new DataBuffer();
ref int id = ref Accessor.GetSecretId(buffer);
id = 100; // Directly modifies private field
PerformanceSyntax
C# · ExpertSnippet

High-Performance Streaming with System.Threading.Channels

System.Threading.Channels provides a highly optimized, asynchronous producer-consumer queue. Unlike ConcurrentQueue, it natively supports async/await for waiting on space (Writer) or items (Reader). Bounded channels allow for backpressure management, ensuring that a fast producer doesn't overwhelm the system memory when the consumer is slow.

snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
using System.Threading.Channels;
var channel = Channel.CreateBounded<int>(new BoundedChannelOptions(100) {
FullMode = BoundedChannelFullMode.Wait
});
// Producer
_ = Task.Run(async () => {
for (int i = 0; i < 1000; i++)
await channel.Writer.WriteAsync(i);
channel.Writer.Complete();
});
// Consumer
await foreach (var item in channel.Reader.ReadAllAsync()) {
Process(item);
}
Async & ConcurrencyPerformance