Recently, I've been working in performance/memory optimization and have stucked in the empty array initialization which uses generic method to initialize empty array:
Code implementation of generic empty array class:
public static class EmptyArray<T>
{
public static readonly T[] Instance;
static EmptyArray()
{
Instance = new T[0];
}
}
So, whenever creating empty array of any type,it has been called as like:
var emptyStringArray = EmptyArray<string>.Instance;
Such empty array declaration has been done in many places of codebase. I am confused how would it be differs in performance while using :
var emptyStringArray = new string[0];
I've asked to above code author and he has replied me :
Basically, all empty arrays are readonly, and are equal to one another, which means that you can use the same instance (which will be created lazily on demand during run-time)… That should reduce the total number of allocations, reduce memory usage and GC pressure, and should result in some improvement
Still, I am not able to understand how would EmptyArray Instance boost the performance in array declaration.
Is there any performance difference in code using following approach :
1st Approach :
var emptyStrArr = EmptyArray<string>.Instance;
var emptyFooArr = EmptyArray<Foo>.Instance;
var emptyBarArr = EmptyArray<Bar>.Instance;
2nd Approach :
var emptyStrArr = new string[0];
var emptyFooArr = new Foo[0];
var emptyBarArr = new Bar[0];