Why events are needed in C Sharp (C#) - Performance Analysis
When we use events in C#, we want to know how the program's work changes as more things listen to those events.
We ask: How does adding more event listeners affect how long the program takes to run?
Analyze the time complexity of the following code snippet.
using System;
public class Button
{
public event Action? Clicked;
public void Click()
{
Clicked?.Invoke();
}
}
This code defines a button that can notify many listeners when it is clicked.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Calling all methods subscribed to the Clicked event.
- How many times: Once per listener each time Click() is called.
Each time the button is clicked, it calls every listener once.
| Number of Listeners (n) | Approx. Calls |
|---|---|
| 1 | 1 call |
| 10 | 10 calls |
| 100 | 100 calls |
Pattern observation: The work grows directly with the number of listeners.
Time Complexity: O(n)
This means the time to notify listeners grows in a straight line as more listeners are added.
[X] Wrong: "Calling an event is always fast and does not depend on listeners."
[OK] Correct: Actually, the program must call each listener one by one, so more listeners mean more work.
Understanding how events scale helps you write responsive programs that stay fast even when many parts listen for changes.
"What if the event had only one listener? How would the time complexity change?"