- Home /
Satisfied
Instantiate/Destroy Garbage Collection advice
I instantiate a gameobject (300verts) every 3secs or less and they get destroyed either 'at random' (wrt time) or in batches on 20, from start to finish.
Should I run Garbage Collection through the course of the game or allow auto GC to do its work?
The case :
I run the following code
function pullIn()
{
var hitColliders = Physics.OverlapSphere(Vector3(0,0,0), detectRadius, allBlockLMask);
for (var i = 0; i < hitColliders.Length; i++)
{
var myTransform : Transform = hitColliders[i].transform;
if ( myTransform.rigidbody.isKinematic == true )
{
myTransform.rigidbody.isKinematic = false;
myTransform.rigidbody.MovePosition(myTransform.rigidbody.position + myTransform.TransformDirection(Vector3.down*blockMoveAmount));
//myTransform.rigidbody.isKinematic = true; // <- (1)
}
}
}
After which I feel a little lagginess for the rest of the game. (The routine works perfectly with no lag - not the issue).
Adding line (1) (marked in the code) solves the problem so I figure the lag is down to constant physics response in my objects, however this doesnt seem to be a problem before the routine.
Should I run Garbage Collection through the course of the game or allow auto GC to do its work? Will it help in this particular case or will the benefits be negligible?
Answer by whydoidoit · Oct 17, 2013 at 03:02 PM
I wouldn't GC during the game - can you not do something about pooling those objects?
Reason being, the version of Mono we are saddled with has only one generation and a GC is going to look at absolutely everything (which is not what happens in the current version of Mono or in the Microsoft versions). The only answer is to allocate a bunch of memory (then deallocate it) and hope you get away with it, or pool everything you can :S
$$anonymous$$y game generally is a great performer so I find myself getting away with a lot. It is happy to instantiate ~450 gameobjects before it stutters at all. I guess it's why I never got round to implementing a pool.
If GC was run in a coroutine, would the impact still be noticable in the main?
I suppose the real question should be, after Unity destroys an object, what residue is left?
Yes it will be impacting the game, because a coroutine isn't a thread and in any case GC has to pause all running threads.
The problem of residue is every byte it ever used will need to be collected...
GC has to pause all running threads
Wow that's proper heavy.
Thanks dude!
So, I tried it anyway, just to see the effects, for completeness :)
I make the call right at the end of my above function and there is absolutely zero impact. Does this mean there is no garbage?
$$anonymous$$aybe, but perhaps just nothing free yet. If you call Destroy it isn't gone until the end of the current frame.