Garbage Spewers

I spent a bit of time on Ayende’s blog today, finally catching up with a series of performance-related blog posts he made whilst working on the .Net profiler (the man’s a living legend, the quality AND quantity of his posts is without equal!)

Whilst reading through the various posts, I came across an unfamiliar term – garbage spewers – in patterns for reducing memory usage. To quote from the blog:

Garbage spewers are pieces of code that allocate a lot of memory that will have to be freed soon afterward.

Ayende highlight a common case of garbage spewers where you continuously concatenate a string using +=:

public string Concat(string[] items)
{
   string result = "";
   foreach(var item in items)
      results += item;
   return result;
}

As you know, string is an immutable type in .Net, that is, a type that cannot be updated once it’s been created. Therefore every time results += item is run a new string variable has to be created to hold the concatenated value of results and item, and the reference pointer stored in the results variable is updated to point to the newly created string.

As Ayende pointed out, this loop can consume a lot of memory which will be cleaned up eventually at the expense of a performance hit as this puts more pressure on the GC.

Other common cases involve loading and converting Data Transfer Objects from the database into various different forms and consuming a lot of memory unnecessarily along the way.