Phase 5 of 30 · Topic 5.4

Local Functions vs Lambda Expressions Memory Internals

1Concept

Local functions compile directly to regular static or instance private methods in IL bytecode without delegate object allocations. Lambdas allocate a closure class on the heap whenever they capture surrounding variables.

2Architecture Diagram

Lambda with Captured Variable:
Heap Allocation ──> `class DisplayClass { int captured; }` ──> Delegate Object

Local Function with `static` Modifier:
Zero Heap Allocation ──> Pure native static method call directly inlined by JIT

3Code Example

C# 13 & .NET 9
using System;

public class LocalFunctionDemo
{
    public static int ProcessNumbers(int x, int y)
    {
        // Static local function guarantees NO closure allocation
        return AddScaled(x, y);

        static int AddScaled(int a, int b) => (a + b) * 2;
    }

    public static void Main()
    {
        int result = ProcessNumbers(15, 5);
        Console.WriteLine($"Local Function Result: {result} (Zero Heap Allocation)");
    }
}

4Expected Output

Local Function Result: 40 (Zero Heap Allocation)

5Key Takeaways

  • Always prefix local functions with `static` if they do not require variable capture.
  • Static local functions cannot accidentally capture outer scope variables.
  • RyuJIT aggressively inlines local functions.