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

I'm using Unity which uses a fairly old C# version, so I'm not sure if this is still the case in new 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 10kb 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.

by Twitchyy via /r/csharp

Leave a Reply