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 }
No comments:
Post a Comment
All comments, questions and other feedback is much appreciated. Thank you!