Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

new object[] {} vs Array.Empty<object>()

Tags:

arrays

c#

People also ask

Why is an array empty?

An empty array is essentially immutable, so caching the instance isn't a problem. And it allows you to forego special-casing empty array creation in your algorithms if you find yourself eyeballing an elegant code path that is creating tons of empty arrays.

What is an empty array C#?

To empty an array in C#, use the Array Clear() method: The Array. Clear method in C# clears i.e.zeros out all elements. In the below example, we have first considered an array with three elements − int[] arr = new int[] {88, 45, 76}; Now we have used the Array.Clear method to zero out all the arrays − Array.

How do you define empty objects?

Using Object. keys will return an Array, which contains the property names of the object. If the length of the array is 0 , then we know that the object is empty.


You're creating an empty array. Which will always be empty, as you cannot change the capacity of the array instance (it just sounds weird to say you can't change it's length, I don't know, why). Every time you do this, you create another instance of an array that can never be used. Doing this a lot may result in wasted GC and memory pressure, thus the warning.

Instead of creating empty arrays, just use Array.Empty<T>() as it suggests. This method returns an array using this static class

internal static class EmptyArray<T>
{
    public readonly static T[] Value;

    static EmptyArray()
    {
        EmptyArray<T>.Value = new T[0];
    }
}

Since it's static and readonly, there's only ever one instance of this empty array in the entire appdomain. An empty array is essentially immutable, so caching the instance isn't a problem. And it allows you to forego special-casing empty array creation in your algorithms, if you find yourself eyeballing an elegant codepath that is creating tons of empty arrays.

Enumerable.Empty<T>() is the Linq to Objects equivalent and is also useful for not wasting allocations for empty stuff.


Using Array.Empty is useful to avoid unnecessary memory allocation. Refer the code from .NET Library itself below:

[Pure]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public static T[] Empty<T>()
{
    Contract.Ensures(Contract.Result<T[]>() != null);
    Contract.Ensures(Contract.Result<T[]>().Length == 0);
    Contract.EndContractBlock();

    return EmptyArray<T>.Value;
}
...
// Useful in number of places that return an empty byte array to avoid unnecessary memory allocation.
internal static class EmptyArray<T>
{
    public static readonly T[] Value = new T[0];
}

Source: https://referencesource.microsoft.com/#mscorlib/system/array.cs,bc9fd1be0e4f4e70