Hello,
During testing my Destroy() implementation, I noticed that once I destroy 1000 objects that was initially visible on my screen, I’m left with 1000+ SpriteBatchItems in the memory.
I took a snapshot, then created and destroyed exactly 1000 objects (with 2D sprites), and then created a snapshot again, and I got the following difference:
Microsoft.Xna.Framework.Graphics.SpriteBatchItem +1,088 +139,264 +139,264 4,416 565,248 565,248
Besides that, I have absolutely no other objects left.
Does anybody know how to track down what are these SpriteBatchItems that are left and how to properly clean it up?
Thank you!
Instead of an allocation, then deallocation, then check, maybe try a different test.
Try just allocating and deallocating several times on a loop. Does your memory grow unbounded, or does it grow to a point, then fall, only to increase again over time?
The reason I ask is that the C# garbage collector isn’t an instantaneous thing. Memory reclamation can be expensive and so it only does it when it thinks it needs to. You can force it using GC.Collect(…) but it’s generally advised to just let it do its own thing and not worry about it. You only need to worry about it when you’re running into problems… which I suspect you aren’t, you’re just running tests?
If GC.Collect doesn’t clean things up, I wonder if MonoGame is doing some caching. It’s a common optimization pattern to pre-allocate a bunch of objects and then, when needed, give them out. When they’re done with, they go back into the queue of pre-allocated items to be recycled on demand. Are these SpriteBatchItems taking up a lot of memory, or only a little bit? If this is the case, you should be able to find evidence of this in the MG source.
Anyway, maybe that’s some things you can try investigating 
1 Like
You are totally right, I just made a test to continuously create and destroy objects without a stop and my memory usage is not increasing at all, so I guess my cleanup works well.
I guess those SpriteBatchItem are part of some internal logic, but it’s not important now as don’t have any memory issue now.
Thank you!
1 Like
Yes, SpriteBatchItems are pooled. There are even some pointers and “unsafe” code involved there in the SpriteBatcher (which I believe is a rare sight in C#) for optimization.
2 Likes