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

Event-driven design pattern in C Sharp (C#) - Time & Space Complexity

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

Scenario Under Consideration

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

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

Each time the event is raised, the program calls every subscriber's response method.

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

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

Final Time Complexity

Time Complexity: O(n)

This means the time to handle an event grows linearly with the number of subscribers listening.

Common Mistake

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

Interview Connect

Understanding how event handling scales helps you design responsive programs and shows you can think about performance in real situations.

Self-Check

"What if the event had to notify subscribers in a nested way, where each subscriber triggers another event? How would the time complexity change?"