Why is less garbage generated if I cache my delegate before subscribing to events?

I'm using Unity which uses an old version of C# so I'm not sure if this is the same for newer versions.

I was looking to reduce the garbage my C# code was generating, and noticed a lot was coming from subscribing to events. Specifically, at one point I have an object subscribe to 80 other object's events like this:

void SubscribeToStuff() { for (int i = 0; i < Objects.Length; i++) { Objects[i].OnSomething += HandleSomething; } } 

The above is generating about 24kb of garbage. However, if I cache the Action delegate and use that to subscribe, there is no garbage at all:

Action _handleAction; void SubscribeToStuff() { _handleAction = HandleSomething; for (int i = 0; i < Objects.Length; i++) { Objects[i].OnSomething += _handleAction; } } 

This doesn't generate any garbage. I'm confused why this happens? Should I just make the delegate prior to subscribing for every event or shouldn't I do this? There doesn't seem to be a downside. I've applied this to all my events now and I've reduced my garbage by about half so far.

As a side question, should I be using a messaging system where the listener subscribes to just a message that any object can send rather than listening to an event on 80 different objects?

by Twitchyy via /r/csharp

Leave a Reply