Async and await keywords in C Sharp (C#) - Time & Space 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?
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 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.
Each item adds a fixed wait time, so total time grows directly with the number of items.
| Input Size (n) | Approx. Operations (waits) |
|---|---|
| 10 | 10 waits of 100ms each |
| 100 | 100 waits of 100ms each |
| 1000 | 1000 waits of 100ms each |
Pattern observation: Total time increases linearly as the list grows.
Time Complexity: O(n)
This means the total time grows in direct proportion to the number of items processed.
[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.
Understanding how async code scales helps you write efficient programs and explain your reasoning clearly in interviews.
"What if we started all the tasks at once and awaited them together? How would the time complexity change?"