Tuesday, February 23, 2010

Generic Empty Array

In certain situations empty arrays of a specific type can be handy. Of course you could always use “new MyType[0]” to instantiate such an empty array and in most situations this will be just fine.

However, if this happens often – like hundreds and thousands of times – then you may want to consider the implementation of a generic empty array. Although it consumes only a few bytes per instance it still contributes to memory consumption and fragmentation and the garbage collector has a few more things to do as well. With a generic empty array a single instance per type is shared throughout your code and those –generally small problems – are avoided in the first place.

Of course this idea is not new. For example check out this conversation on stackoverflow. However the code given there contains a small glitch and doesn’t compile, so here is the source code for the same thing with that glitch resolved:

   25 namespace csUnit.Common {

   26    public static class EmptyArray<T> {

   27       private static readonly T[] Empty = new T[0];

   28       public static T[] Instance {

   29          get { return Empty; }

   30       }

   31    }

   32 }

But wait, there is one more: When you use an array as a return value for a method you may also want to consider reading Eric Lippert’s thoughts on the subject. It definitely doesn’t hurt and may make your code more efficient and improve the design of it.

0 comments:

Post a Comment

All comments, questions and other feedback is much appreciated. Thank you!