0
0
C Sharp (C#)programming~5 mins

Lambda with captures (closures) in C Sharp (C#) - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Lambda with captures (closures)
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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).
How Execution Grows With Input

Each new number means one more multiplication and print.

Input Size (n)Approx. Operations
1010 multiplications and prints
100100 multiplications and prints
10001000 multiplications and prints

Pattern observation: The work grows directly with the number of items.

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows in a straight line as the input size grows.

Common Mistake

[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.

Interview Connect

Understanding how lambdas with captures behave helps you explain code efficiency clearly and confidently.

Self-Check

"What if the lambda captured a collection and iterated inside itself for each call? How would the time complexity change?"