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

Async and await keywords in C Sharp (C#) - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Async and await keywords
O(n)
Understanding Time Complexity

When using async and await, we want to understand how the program's work changes as input grows.

We ask: How does waiting for tasks affect the total time spent?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


async Task ProcessItemsAsync(List<int> items)
{
    foreach (var item in items)
    {
        await Task.Delay(100); // Simulate async work
    }
}
    

This code processes each item in a list, waiting asynchronously for 100 milliseconds per item.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The foreach loop runs once per item.
  • How many times: Exactly as many times as there are items in the list.
How Execution Grows With Input

Each item adds a fixed wait time, so total time grows directly with the number of items.

Input Size (n)Approx. Operations (waits)
1010 waits of 100ms each
100100 waits of 100ms each
10001000 waits of 100ms each

Pattern observation: Total time increases linearly as the list grows.

Final Time Complexity

Time Complexity: O(n)

This means the total time grows in direct proportion to the number of items processed.

Common Mistake

[X] Wrong: "Using async and await makes the code run instantly or in constant time."

[OK] Correct: Async lets the program wait without blocking, but the total work still depends on how many items you process.

Interview Connect

Understanding how async code scales helps you write efficient programs and explain your reasoning clearly in interviews.

Self-Check

"What if we started all the tasks at once and awaited them together? How would the time complexity change?"