Why you should stay away from the delegates in Unity

Viktor Zatorskyi
2 min readFeb 17, 2018

Well, not in all cases, but you definitely need to think twice when using them in production.

Event driven architecture has become extremely popular in Unity because it eases communication between components. Modern UI is probably unthinkable without events as well. Events in C# is backed by delegates and in this write-up I’m focusing on multicast delegates.

So let’s check what’s wrong with delegates by example. I have instantiated ~1000 objects which are all subscribed to one delegate

Manager.OnSomethingHappend += Callback;

In the following screenshot, we can see what is happening when we add one more object which subscribes to the event as well.

Let’s look what happens in MulticastDelegate.CombineImpl() source

It’s an immutable list which is recreated each time we subscribe to an event. What about newer versions of Mono Runtime which comes with Unity 2017? It uses Array.Copy , so basically each time we subscribe/unsubscribe we create new array (source).

What alternatives do we have except creating own delegate implementation? Unfortunately, there is no silver bullet and we need to use a bit of every solution in different scenarios.

Interfaces should help a bit. Sure, it’s not a perfect approach to replace each event with interfaces. This will bloat your code or will make it less readable. However, it’s handy to have a couple of generic callback interfaces for occasional usage and specific (very descriptive) interfaces for the often used callbacks.

Delegates could be still used if a list of subscribers is quite small, but you don’t want an army of minions to listen for one event for sure.

--

--