EventHandler delegate pattern in C Sharp (C#) - Time & Space Complexity
When using the EventHandler delegate pattern, it's important to understand how the program's work grows as more event subscribers are added.
We want to know how the time to notify all listeners changes when the number of subscribers increases.
Analyze the time complexity of the following code snippet.
public class Publisher
{
public event EventHandler? OnChange;
public void RaiseEvent()
{
OnChange?.Invoke(this, EventArgs.Empty);
}
}
This code defines a publisher that raises an event notifying all subscribed listeners.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Invoking each subscribed event handler in the delegate invocation list.
- How many times: Once for each subscriber registered to the event.
Each time the event is raised, the program calls every subscriber in order.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 calls to subscribers |
| 100 | 100 calls to subscribers |
| 1000 | 1000 calls to subscribers |
Pattern observation: The number of calls grows directly with the number of subscribers.
Time Complexity: O(n)
This means the time to notify all listeners grows linearly as more subscribers join.
[X] Wrong: "Raising the event takes the same time no matter how many subscribers there are."
[OK] Correct: Each subscriber must be called one by one, so more subscribers mean more calls and more time.
Understanding how event notifications scale helps you write responsive and efficient programs that handle many listeners gracefully.
"What if the event handlers themselves raise other events? How would that affect the overall time complexity?"