Returning values from async methods in C Sharp (C#) - Time & Space 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.
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 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.
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 |
|---|---|
| 10 | About 10 waits and adds |
| 100 | About 100 waits and adds |
| 1000 | About 1000 waits and adds |
Pattern observation: The work grows directly with the number of items; double the items, double the work.
Time Complexity: O(n)
This means the time to complete grows in a straight line with the number of elements to process.
[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.
Understanding how async methods handle work step-by-step helps you explain performance clearly and shows you know how to reason about real code.
What if we replaced the await inside the loop with a single await after the loop? How would the time complexity change?