⚡ Delegate Overhead? Use Function Pointers.
Delegates are fast, but not zero-cost. Function pointers (C# 9+) call native code or high-frequency callbacks with minimal overhead.
📝 Basic Function Pointer
unsafe
{
// Delegate (managed)
Func addDelegate = (a, b) => a + b;
// Function pointer (unmanaged)
delegate* addPointer = &Add;
int result1 = addDelegate(5, 3); // Delegate invoke
int result2 = addPointer(5, 3); // Function pointer call (faster)
}
static int Add(int a, int b) => a + b;
🎯 Real-World Use
public unsafe class FastSort
{
private delegate* _comparer;
public FastSort(delegate* comparer)
{
_comparer = comparer;
}
public void Sort(int[] array)
{
// Fast comparison without delegate overhead
Array.Sort(array, (a, b) => _comparer(a, b));
}
}
// Usage
static int CompareInts(int a, int b) => a.CompareTo(b);
unsafe
{
var sorter = new FastSort(&CompareInts);
sorter.Sort(new[] { 5, 2, 8, 1, 9 });
}
💡 When to Use
- P/Invoke to native C/C++ code
- High-frequency callbacks (100k+ calls/second)
- Game engines, real-time systems
- When delegate allocation matters
- Requires unsafe context (compiler flag)
“Sorting 50M items. Delegate comparer was bottleneck. Function pointer made it 20% faster. For high-performance code, every instruction matters.”
