Lambda with captures (closures) in C Sharp (C#) - Time & Space Complexity
Let's see how using a lambda that captures variables affects how long a program takes to run.
We want to know how the work grows when the input gets bigger.
Analyze the time complexity of the following code snippet.
int[] numbers = {1, 2, 3, 4, 5};
int factor = 2;
Func multiply = x => x * factor;
foreach (var num in numbers)
{
Console.WriteLine(multiply(num));
}
This code multiplies each number in an array by a captured variable using a lambda.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The foreach loop runs once for each number in the array.
- How many times: It runs exactly as many times as there are numbers (n times).
Each new number means one more multiplication and print.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 multiplications and prints |
| 100 | 100 multiplications and prints |
| 1000 | 1000 multiplications and prints |
Pattern observation: The work grows directly with the number of items.
Time Complexity: O(n)
This means the time to finish grows in a straight line as the input size grows.
[X] Wrong: "Capturing a variable in a lambda makes the code slower for each call."
[OK] Correct: Capturing just holds a reference to the variable; the lambda runs once per item just like normal code.
Understanding how lambdas with captures behave helps you explain code efficiency clearly and confidently.
"What if the lambda captured a collection and iterated inside itself for each call? How would the time complexity change?"