Delegates as callback pattern in C Sharp (C#) - Time & Space Complexity
When using delegates as callbacks, it is important to understand how the program's running time changes as the input grows.
We want to know how many times the callback runs and how that affects overall execution time.
Analyze the time complexity of the following code snippet.
public delegate void Callback(int value);
public void ProcessItems(int[] items, Callback callback)
{
foreach (var item in items)
{
callback(item);
}
}
This code runs a callback delegate on each item in an array.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The foreach loop that calls the callback for each item.
- How many times: Once for every element in the input array.
As the number of items grows, the callback runs more times, directly increasing total work.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 callback calls |
| 100 | 100 callback calls |
| 1000 | 1000 callback calls |
Pattern observation: The work grows in a straight line with input size.
Time Complexity: O(n)
This means the time to run grows directly in proportion to the number of items.
[X] Wrong: "The callback runs only once, so time is constant regardless of input size."
[OK] Correct: The callback runs once for each item, so more items mean more calls and more time.
Understanding how callbacks affect time helps you explain how your code scales and shows you can reason about program efficiency.
"What if the callback itself contains a loop over the entire array? How would the time complexity change?"