I had the pleasure of creating loads of garbage while trying to decouple things with just a single, simple thing: Events. As Jackson Dunstan has shown C#-Events are heavily allocating memory and thats a unwanted pitfall in game programming. Creating 4000 objects on the fly with event allocation and everything needed for that Unity is collecting roughly 130 MB (!) of garbage - and my game just hangs around. The solution is quite simple:

public event EventHandler Event
{
    add
    {
        eventListener.Add(value);
    }
    remove
    {
        eventListener.Remove(value);
    }
}

private List<EventHandler> eventListener = new List<EventHandler>();

private void OnEvent()
{
    for (int i = eventListener.Count - 1; i >= 0; i--)
    {
        eventListener[i]();
    }
}

The reverse for-loop is necessary for handling recently removed event handlers (i.e. Event is called, and Object unsubscribes the event). Simple, powerfull and without creating any garbage.

Previous Post Next Post