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

Event unsubscription and memory in C Sharp (C#) - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Event unsubscription and memory
O(n)
Understanding Time Complexity

When working with events in C#, it's important to understand how unsubscribing affects program performance and memory.

We want to see how the time to unsubscribe grows as more event handlers are attached.

Scenario Under Consideration

Analyze the time complexity of unsubscribing event handlers from an event.


public class Publisher
{
    public event EventHandler? OnChange;

    public void UnsubscribeAll()
    {
        if (OnChange == null) return;
        foreach (Delegate d in OnChange.GetInvocationList())
        {
            OnChange -= (EventHandler)d;
        }
    }
}
    

This code removes all handlers subscribed to the OnChange event one by one.

Identify Repeating Operations

Look for loops or repeated actions in the code.

  • Primary operation: Looping through each subscribed event handler.
  • How many times: Once for each handler attached to the event.
How Execution Grows With Input

The time to unsubscribe grows as the number of handlers increases.

Input Size (n)Approx. Operations
10About 10 loop steps to remove handlers
100About 100 loop steps to remove handlers
1000About 1000 loop steps to remove handlers

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

Final Time Complexity

Time Complexity: O(n)

This means the time to unsubscribe all handlers grows linearly with how many handlers there are.

Common Mistake

[X] Wrong: "Unsubscribing from an event is always a constant time operation."

[OK] Correct: Because unsubscribing here loops through all handlers, so more handlers mean more time needed.

Interview Connect

Understanding how event unsubscription scales helps you write efficient and memory-safe C# programs, a useful skill in many coding situations.

Self-Check

What if we stored handlers in a different data structure that allowed direct removal? How would the time complexity change?