Garbage Spewers

I spent a bit of time on Ayende’s blog today, final­ly catch­ing up with a series of per­for­mance-relat­ed blog posts he made whilst work­ing on the .Net pro­fil­er (the man’s a liv­ing leg­end, the qual­i­ty AND quan­ti­ty of his posts is with­out equal!)

Whilst read­ing through the var­i­ous posts, I came across an unfa­mil­iar term – garbage spew­ers — in pat­terns for reduc­ing mem­o­ry usage. To quote from the blog:

Garbage spew­ers are pieces of code that allo­cate a lot of mem­o­ry that will have to be freed soon after­ward.

Ayende high­light a com­mon case of garbage spew­ers where you con­tin­u­ous­ly con­cate­nate 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 can­not be updat­ed once it’s been cre­at­ed. There­fore every time results += item is run a new string vari­able has to be cre­at­ed to hold the con­cate­nat­ed val­ue of results and item, and the ref­er­ence point­er stored in the results vari­able is updat­ed to point to the new­ly cre­at­ed string.

As Ayende point­ed out, this loop can con­sume a lot of mem­o­ry which will be cleaned up even­tu­al­ly at the expense of a per­for­mance hit as this puts more pres­sure on the GC.

Oth­er com­mon cas­es involve load­ing and con­vert­ing Data Trans­fer Objects from the data­base into var­i­ous dif­fer­ent forms and con­sum­ing a lot of mem­o­ry unnec­es­sar­i­ly along the way.