Why is the function "Destroy" taking so much time

I’m seeing a vast amount of time disappearing in the function “Destroy” when profiling my game on an iPad1 (it’s also a factor on an iPad2 grab but orders of magnitude less painful). At the point I was recording I was doing a lot of procedural mesh creation and so destroying last frame’s mesh each update. Most likely it’s related to that?

Just wondering if anyone can shed any light on what exactly could be going on, i.e what could be being destroyed that would take so long (and why)? Most importantly is there anything I can do to eliminate or lessen the expense?

Hopefully you can see a screen-grab from the profiler below:
alt text

Thanks!

2 Answers

2

Ok, so I’ve reworked my procedural mesh stuff to re-use the same mesh rather than calling Mesh.Destroy and creating a new one each time and that seems to have brought the “Destroy” time down considerably. I guess the take-away lesson: destroying stuff is slow, avoid.

Certainly it would be unusual in any game to be creating or Destroying a GameObject or a Component every frame.

Be sure to watch this video: http://www.youtube.com/watch?v=IX041ZvgQKE even if you don't use C# you can use the object pooling script he writes, which is pretty awesome.

There isn't a lot you can do about arrays - Unity copies them every time they pass into or out of a setter/getter in the Unity API. Best you can do is minimise other copies. Maybe using arrays of same size will trigger optimisations inside Unity.

That’s called Object Pooling, isn’t it?

Yeah, exactly.

Actually, it's not. Object pooling is where you collect no-longer-used objects and reuse them next time one is needed. Trepan is doing better: reusing the object immediately, so not having the overhead of managing the pool.

That's just a pool of one :p

I know you're joking, but it's exactly that sort of clean generic thinking that probably created the problem in the first place. There is a joke that whenever a programmer needs boiled water, he first empties the kettle in order to start from a known initial state.