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

EventHandler delegate pattern in C Sharp (C#) - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: EventHandler delegate pattern
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

Each time the event is raised, the program calls every subscriber in order.

Input Size (n)Approx. Operations
1010 calls to subscribers
100100 calls to subscribers
10001000 calls to subscribers

Pattern observation: The number of calls grows directly with the number of subscribers.

Final Time Complexity

Time Complexity: O(n)

This means the time to notify all listeners grows linearly as more subscribers join.

Common Mistake

[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.

Interview Connect

Understanding how event notifications scale helps you write responsive and efficient programs that handle many listeners gracefully.

Self-Check

"What if the event handlers themselves raise other events? How would that affect the overall time complexity?"