Event-driven design pattern in C Sharp (C#) - Time & Space Complexity
When using the event-driven design pattern, it's important to understand how the program's work grows as more events happen.
We want to see how the number of events affects the time the program takes to respond.
Analyze the time complexity of the following code snippet.
public class Publisher
{
public event Action? OnChange;
public void RaiseEvent()
{
OnChange?.Invoke();
}
}
public class Subscriber
{
public void Respond() { /* handle event */ }
}
This code shows a publisher that raises an event and subscribers that respond when the event happens.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Invoking all subscriber methods when the event is raised.
- How many times: Once per event raised, calling each subscriber's response method.
Each time the event is raised, the program calls every subscriber's response method.
| Input Size (n subscribers) | Approx. Operations per Event |
|---|---|
| 10 | 10 calls |
| 100 | 100 calls |
| 1000 | 1000 calls |
Pattern observation: The work grows directly with the number of subscribers.
Time Complexity: O(n)
This means the time to handle an event grows linearly with the number of subscribers listening.
[X] Wrong: "Raising an event always takes the same time no matter how many subscribers there are."
[OK] Correct: Each subscriber adds work because the event calls their method, so more subscribers mean more calls and more time.
Understanding how event handling scales helps you design responsive programs and shows you can think about performance in real situations.
"What if the event had to notify subscribers in a nested way, where each subscriber triggers another event? How would the time complexity change?"