How async execution flows in C Sharp (C#) - Performance & Efficiency
When we use async code, the program does some work now and some later without waiting. We want to see how this affects the total time the program takes.
How does the program's running time grow when using async calls?
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
Console.WriteLine(item);
}
}
This code processes a list of items one by one, waiting asynchronously for 100 milliseconds each time.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The foreach loop runs once for each item in the list.
- How many times: Exactly as many times as there are items (n times).
Each item causes a 100ms wait, so total time grows as more items are added.
| Input Size (n) | Approx. Operations (waits) |
|---|---|
| 10 | 10 waits x 100ms = 1 second |
| 100 | 100 waits x 100ms = 10 seconds |
| 1000 | 1000 waits x 100ms = 100 seconds |
Pattern observation: The total time grows directly with the number of items; doubling items doubles total wait time.
Time Complexity: O(n)
This means the total time grows in a straight line as the number of items increases.
[X] Wrong: "Async means all items run at the same time, so total time stays the same no matter how many items."
[OK] Correct: Here, the code waits for each item one after another, so the waits add up, not run in parallel.
Understanding how async code runs step-by-step helps you explain program speed clearly and shows you know how to write efficient code.
"What if we changed the foreach loop to start all tasks at once and then awaited them together? How would the time complexity change?"