title: Unity3D: optimize garbage collection
body: <p>Unity3D <a href="http://docs.unity3d.com/Documentation/Manual/Profiler.html" rel="noreferrer">Profiler</a> gives me spikes that is mostly about garbage collection. In the screenshot below, the three red spikes represent three stalls that I had in my gameplay. Each of these stalls are 100+ms and most of the time was spent on <code>TrackDependencies</code>. </p>
  
  <p>According to <a href="http://docs.unity3d.com/Documentation/Manual/UnderstandingAutomaticMemoryManagement.html" rel="noreferrer">Unity instruction</a>, I tried adding this to my code:</p>
  
  <pre><code>if (Time.frameCount % 30 == 0)
  {
      System.GC.Collect();
  }
  </code></pre>
  
  <p>This didn't help. I still have spikes and they still take 100+ms. What exactly is going on and what can I do to optimize my game?</p>
  
  <p>PS: </p>
  
  <p>I am dynamically creating and destroying a lot of <code>GameObject</code>s in my game. Could that be a problem?</p>
  
  <p>I don't have string concatenation in a loop or array as return value as caveated in <a href="http://docs.unity3d.com/Documentation/Manual/UnderstandingAutomaticMemoryManagement.html" rel="noreferrer">the post</a>.</p>
  
  <p><img src="https://i.stack.imgur.com/r4yTa.png" alt="profiler"></p>