Memory Leak Issues (Delegate.Clone?)

I’m trying to figure out what’s causing a particular memory leak in my code. The memory usage goes up quite rapidly whenever I load chunks in my voxel engine, and never goes back down when they get unloaded. After ruling out several other things, I came across this:

My chunks are not Game Objects and do not use Game Objects. However, I still want the ability to run update loops on the active chunks surrounding the player.

When the chunk loader creates chunks around the player, those chunks get subscribed to an event. This event is triggered every frame in the Update method of the Engine game object.

This way, I can get an Update on each active chunk by directing it through an event. And when these chunks get unloaded, they are also unsubscribed from this event and no longer receive the update. I’ve tested this and this works fine - the correct number of chunks are subscribed and the correct number are unsubscribed.

Looking through the profiler to find where this memory is being allocated, I came across 2522 calls to “Delegate.Clone()” in the Chunk.SetActive function, which is the function that subscribes the chunk to the update event.There were only 13 chunks set active there, but there were 2522 calls to Clone and 256 KB of memory allocated.

This appears to happen very frequently, and this memory seems to never be collected by the garbage collector.

Any idea why this might happen? I can’t seem to find anything else allocating all this memory in here.

Thanks!

Can you share some relevant code (like your SetActive for starters)? We might be able to help debug.

SetActive does only two things:

-Sets an active flag on the chunk to true (bool). That flag isn’t relevant to this issue. It has the job of ensuring chunks aren’t subscribed more than once. And I’ve tested and confirmed that they aren’t.

-Subscribes the chunk’s UpdateChunk function to the event that I trigger every frame.

( Engine.OnGameEvent += UpdateChunk; )

I’m not sure what else is relevant here… how do you get 2522 clone calls from 13 subscribes to an event? There were 169 items subscribed prior to subscribing these new 13, if that’s relevant.

That’s your problem right there. Delegates are immutable.

1 Like

You’re right… so each time I subscribe an event, it has to create a new delegate. Still, there were only 13 adds to it, so I was a bit surprised to see 2522 calls. In either case, I doubt this is actually an issue… since it turns out my memory leak actually was related to something else entirely. (If this is leaking memory, it’s not a significant amount).

Hm, it’s the ‘clone’, not the ‘combine’… well, I suppose this will make sense if I look into it more deeply with this knowledge.

Thanks for that hint.

Well the profiller hierarchy shows that Combine calls clone. And the reason you have so many call is probably this:

    public static Delegate Combine(params Delegate[] delegates)
    {
      if (delegates == null || delegates.Length == 0)
        return (Delegate) null;
      Delegate a = delegates[0];
      for (int index = 1; index < delegates.Length; ++index)
        a = Delegate.Combine(a, delegates[index]);
      return a;
    }

That is the code which is run when you add delegates, I believe. It explains why you have so many calls.

1 Like

Makes sense. I have changed my chunk loading/unloading to use a more efficient system now that I know how that works.

Thanks again.

That’s actually the code for Delegate.Combine(…), not MultiCastDelegate.CombineImp(…), which is where the problem lies. Note it doesn’t contain any calls to ‘Clone’, nor does it even the version called since it’s the array param version of the method. Furthermore, that looks more like the ‘.net’ code, and not the ‘mono’ version.

And the reason it exists is because of the way the version of Mono that is used by Unity designed their delegates rather poorly.

This is the offending code in mono:

    /// <summary>
    /// Combines this <see cref="T:System.Delegate"/> with the specified <see cref="T:System.Delegate"/> to form a new delegate.
    /// </summary>
    ///
    /// <returns>
    /// A delegate that is the new root of the <see cref="T:System.MulticastDelegate"/> invocation list.
    /// </returns>
    /// <param name="follow">The delegate to combine with this delegate. </param><exception cref="T:System.ArgumentException"><paramref name="follow"/> does not have the same type as this instance.</exception><exception cref="T:System.MemberAccessException">Cannot create an instance of an abstract class, or this member was invoked with a late-binding mechanism. </exception>
    protected override sealed Delegate CombineImpl(Delegate follow)
    {
      if (this.GetType() != follow.GetType())
        throw new ArgumentException(Locale.GetText("Incompatible Delegate Types."));
      MulticastDelegate multicastDelegate1 = (MulticastDelegate) follow.Clone();
      multicastDelegate1.SetMulticastInvoke();
      MulticastDelegate multicastDelegate2 = multicastDelegate1;
      for (MulticastDelegate multicastDelegate3 = ((MulticastDelegate) follow).prev; multicastDelegate3 != null; multicastDelegate3 = multicastDelegate3.prev)
      {
        multicastDelegate2.prev = (MulticastDelegate) multicastDelegate3.Clone();
        multicastDelegate2 = multicastDelegate2.prev;
      }
      multicastDelegate2.prev = (MulticastDelegate) this.Clone();
      MulticastDelegate multicastDelegate4 = multicastDelegate2.prev;
      for (MulticastDelegate multicastDelegate3 = this.prev; multicastDelegate3 != null; multicastDelegate3 = multicastDelegate3.prev)
      {
        multicastDelegate4.prev = (MulticastDelegate) multicastDelegate3.Clone();
        multicastDelegate4 = multicastDelegate4.prev;
      }
      return (Delegate) multicastDelegate1;
    }

Note it’s very different from how .Net does it:

    /// <summary>
    /// Combines this <see cref="T:System.Delegate"/> with the specified <see cref="T:System.Delegate"/> to form a new delegate.
    /// </summary>
    ///
    /// <returns>
    /// A delegate that is the new root of the <see cref="T:System.MulticastDelegate"/> invocation list.
    /// </returns>
    /// <param name="follow">The delegate to combine with this delegate. </param><exception cref="T:System.ArgumentException"><paramref name="follow"/> does not have the same type as this instance.</exception><exception cref="T:System.MemberAccessException">Cannot create an instance of an abstract class, or this member was invoked with a late-binding mechanism. </exception>
    [SecuritySafeCritical]
    protected override sealed Delegate CombineImpl(Delegate follow)
    {
      if (follow == null)
        return (Delegate) this;
      if (!Delegate.InternalEqualTypes((object) this, (object) follow))
        throw new ArgumentException(Environment.GetResourceString("Arg_DlgtTypeMis"));
      MulticastDelegate multicastDelegate = (MulticastDelegate) follow;
      int num = 1;
      object[] objArray1 = multicastDelegate._invocationList as object[];
      if (objArray1 != null)
        num = (int) multicastDelegate._invocationCount;
      object[] objArray2 = this._invocationList as object[];
      if (objArray2 == null)
      {
        int invocationCount = 1 + num;
        object[] invocationList = new object[invocationCount];
        invocationList[0] = (object) this;
        if (objArray1 == null)
        {
          invocationList[1] = (object) multicastDelegate;
        }
        else
        {
          for (int index = 0; index < num; ++index)
            invocationList[1 + index] = objArray1[index];
        }
        return (Delegate) this.NewMulticastDelegate(invocationList, invocationCount);
      }
      else
      {
        int index1 = (int) this._invocationCount;
        int invocationCount = index1 + num;
        object[] objArray3 = (object[]) null;
        if (invocationCount <= objArray2.Length)
        {
          objArray3 = objArray2;
          if (objArray1 == null)
          {
            if (!this.TrySetSlot(objArray3, index1, (object) multicastDelegate))
              objArray3 = (object[]) null;
          }
          else
          {
            for (int index2 = 0; index2 < num; ++index2)
            {
              if (!this.TrySetSlot(objArray3, index1 + index2, objArray1[index2]))
              {
                objArray3 = (object[]) null;
                break;
              }
            }
          }
        }
        if (objArray3 == null)
        {
          int length = objArray2.Length;
          while (length < invocationCount)
            length *= 2;
          objArray3 = new object[length];
          for (int index2 = 0; index2 < index1; ++index2)
            objArray3[index2] = objArray2[index2];
          if (objArray1 == null)
          {
            objArray3[index1] = (object) multicastDelegate;
          }
          else
          {
            for (int index2 = 0; index2 < num; ++index2)
              objArray3[index1 + index2] = objArray1[index2];
          }
        }
        return (Delegate) this.NewMulticastDelegate(objArray3, invocationCount, true);
      }
    }

This is because .Net implements the MultiCastDelegate as an object array.

Mono on the other hand implements it as a LinkedList, and uses the Delegate itself as the node for the LinkedList. And because delegates were intended to be treated as immutable, it goes about it by duplicating EVERY node in the LinkedList every time the list is changed… since the node data is in the delegate and should be treated immutable… O_O.

That is HORRIBLE design.

But yeah, that’s what is causing the problem. Every time you add a new delegate to the array. It clones all the previous delegates inside the event already.

1 = 0 clones
2 = 2 clones
3 = 5 clones (2 + 3)
4 = 9 clones (2 + 3 + 4)
…
13 = 90 clones (2 + 3 + 4 + 5 + … + 13)
(these are the results I get when I test it on my system, which seem right looking at the code behind it)

You probably already have several delegates registered when you go and add those 13 new delegates in your profiler. Which would account for the extra calls to clone. As it would have to dupe down the existing chain as well.

4 Likes

Note, garbage collection should be cleaning up those orphaned delegates though.

It does in my test that I did here. It doesn’t clean up immediately, as is how GC goes about its business, but they still do get cleaned up in due time.

Yeah, this probably is properly cleaned up - I had a problem with meshes causing the memory leaks. But for whatever reason I couldn’t find where that memory was leaking (only found this memory allocation).

But the mesh count constantly going up and never falling back down informed me that it was a mesh problem instead.

Still, good to know how this was working. I had no idea :slight_smile:

Yes, it is the .Net version, which I assumed functioned the same, though I see it does not. But the code I pasted does indeed call CombineImpl() eventually. The code I pasted called this function:

 public static Delegate Combine(Delegate a, Delegate b)
    {
      if (a == null)
        return b;
      else
        return a.CombineImpl(b);
    }

But yes, I think you found the source of the problem.

Where did you get the Mono source? Just wondering if you decompiled a DLL, or if it’s publicly available.

Decompiled the mscorlib.dll that can be found in your Unity install directory.

…programs…\Unity\Editor\Data\Mono\lib\mono\2.0