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

Deferred execution behavior in C Sharp (C#) - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Deferred execution behavior
O(n)
Understanding Time Complexity

Deferred execution means some code waits to run until its results are needed.

We want to see how this waiting affects how long the program takes as input grows.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


var numbers = Enumerable.Range(1, n);
var query = numbers.Where(x => x % 2 == 0);

foreach (var num in query)
{
    Console.WriteLine(num);
}

This code generates a sequence of numbers from 1 to n, sets up a filter for even numbers, and then prints them.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Checking each number in the range (1 to n) to see if it is even during enumeration.
  • How many times: n times (once per number).
How Execution Grows With Input

As n grows, the program checks each of the n numbers during iteration.

Input Size (n)Approx. Operations
10About 10 checks (5 prints)
100About 100 checks (50 prints)
1000About 1000 checks (500 prints)

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

Final Time Complexity

Time Complexity: O(n)

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

Common Mistake

[X] Wrong: "The filtering happens immediately when the query is created, so it costs time right away."

[OK] Correct: The filtering only happens when we start looping through the query, not when we set it up. So the cost is delayed until use.

Interview Connect

Understanding deferred execution helps you explain how your code manages work efficiently by waiting to do things only when needed.

Self-Check

"What if we replaced the Where filter with a Select that transforms each number? How would the time complexity change?"