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

How async execution flows in C Sharp (C#) - Performance & Efficiency

Choose your learning style9 modes available
Time Complexity: How async execution flows
O(n)
Understanding Time Complexity

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?

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
        Console.WriteLine(item);
    }
}

This code processes a list of items one by one, waiting asynchronously for 100 milliseconds each time.

Identify Repeating Operations

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

Each item causes a 100ms wait, so total time grows as more items are added.

Input Size (n)Approx. Operations (waits)
1010 waits x 100ms = 1 second
100100 waits x 100ms = 10 seconds
10001000 waits x 100ms = 100 seconds

Pattern observation: The total time grows directly with the number of items; doubling items doubles total wait time.

Final Time Complexity

Time Complexity: O(n)

This means the total time grows in a straight line as the number of items increases.

Common Mistake

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

Interview Connect

Understanding how async code runs step-by-step helps you explain program speed clearly and shows you know how to write efficient code.

Self-Check

"What if we changed the foreach loop to start all tasks at once and then awaited them together? How would the time complexity change?"