Oozi vs Garbage Collector
12 03 11 - 18:08 Yesterday I finally managed to go down with runtime garbage generation to zero bytes per second. You think it's easy task, just use pooling and avoid String concatenations? Well, that's what I thought some time ago. Unfortunately I was wrong. Here are some things that are good to know if you're going for garbage-free XNA-Xbox game.1) StringBuilder isn't garbage free. Surprised? I was pretty sure that this class was designed to avoid garbage. Unfortunately, it works garbage-free only for String and char Append methods. If you want to append int, garbage will be generated. Fortunately I found a free implementation of garbage-free Append methods on Gavin Pugh's blog (thanks Gavin!).
2) XACT isn't garbage free. Furthermore, SoundEffect.Play() isn't garbage free as well. What can you do? The only thing you can do to play sounds and avoid garbage is to keep a pool of SoundEffectInstances. However, you can't keep more than 300 instances at once on Xbox, if you do it will crash. I included my code that manages a pool of SoundEffectInstances at the end of this post.
3) Foreach loop might generate garbage in some cases. Especially when you're iterating over a Collection, i.e. Dictionary.Keys collection. You can read more on foreach garbage here.
int soundEffectInstancesCount;
Dictionary< SoundEffect, List< SoundEffectInstance > > SingleInstancesCache
= new Dictionary< SoundEffect, List< soundeffectinstance > >();
public void playSingleSound( SoundEffect soundEffect, float volume )
{
List < SoundEffectInstance> instances;
if (!SingleInstancesCache.ContainsKey(soundEffect))
{
instances = new List(10);
SingleInstancesCache[soundEffect] = instances;
}
else
instances = SingleInstancesCache[soundEffect];
for (int iSoundInstance = 0; iSoundInstance < instances.Count; ++iSoundInstance)
{
SoundEffectInstance instance = instances[iSoundInstance];
if (instance.State == SoundState.Stopped)
{
instance.Play();
return;
}
}
SoundEffectInstance newInstance = soundEffect.CreateInstance();
SingleInstancesCache[soundEffect].Add(newInstance);
newInstance.Play();
soundEffectInstancesCount++;
if (soundEffectInstancesCount % 20 == 0)
System.Diagnostics.Debug.WriteLine("Sound effect instances count over "
+ soundEffectInstancesCount);
}
Trackback link: http://mojabiblioteczka.pl/pivot/tb.php?tb_id=14