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

Returning values from async methods in C Sharp (C#) - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Returning values from async methods
O(n)
Understanding Time Complexity

When we use async methods that return values, it's important to know how the time to get results grows as input changes.

We want to see how the method's work increases when it waits for and processes data asynchronously.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


public async Task<int> SumAsync(int[] numbers)
{
    int sum = 0;
    foreach (var num in numbers)
    {
        await Task.Delay(1); // Simulate async work
        sum += num;
    }
    return sum;
}
    

This method adds all numbers in an array asynchronously, waiting a bit for each number before adding it.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through each number in the array and awaiting a small delay.
  • How many times: Once for each element in the input array.
How Execution Grows With Input

As the array gets bigger, the method waits and adds more times, so the total work grows with the number of items.

Input Size (n)Approx. Operations
10About 10 waits and adds
100About 100 waits and adds
1000About 1000 waits and adds

Pattern observation: The work grows directly with the number of items; double the items, double the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to complete grows in a straight line with the number of elements to process.

Common Mistake

[X] Wrong: "Because the method is async, it runs instantly and time doesn't grow with input size."

[OK] Correct: Async means it can wait without blocking, but the total work still depends on how many items it processes one by one.

Interview Connect

Understanding how async methods handle work step-by-step helps you explain performance clearly and shows you know how to reason about real code.

Self-Check

What if we replaced the await inside the loop with a single await after the loop? How would the time complexity change?