Enumerable.Empty vs new T[0]

The need for creating an Empty array/collection rises quite often in most applications. This, normally presents us with two options.

  • Using the Constructor, new T[0];
  • Using the extension method, Enumerable.Empty

Let’s dive a bit deeper into both and examine how both these options work and differ.

Using new T[0]

Creating an empty array with Array Construction syntax is as follows.

var collection = new T[0];

What exactly happens behind the scenes. Let’s examine the following code.

var collection1 = new string[0];
var collection2 = new string[0];
object.ReferenceEquals(collection1,collection2).Dump();

Output of above code would be

False

The reason for this is self-explanatory. Each call to ‘new T[0]’ create a new Empty array in the memory. Both these, are as noticable, separate instances. What happens with Enumerable.Empty then ? Let’s examine that next.

Using Enumerable.Empty

Consider the complimentary code using Enumerable.Empty approach.

var collection1 = Enumerable.Empty<string>();
var collection2 = Enumerable.Empty<string>();
var result = object.ReferenceEquals(collection1,collection2);

What would be output of code in above scenario ? As you might have guessed, the output would be true.

Output

True

Enumerable.Empty caches the result for calls and reuses it later on. As MSDN states it

The Empty<TResult>() method caches an empty sequence of type TResult. When the object it returns is enumerated, it yields no elements.

This can be further verified by checking out the source code of Enumerable.Empty.

public static IEnumerable<TResult> Empty<TResult>()
{
return EmptyEnumerable<TResult>.Instance;
}
internal class EmptyEnumerable<TElement>
{
public static readonly TElement[] Instance = new TElement[0];
}

This difference might be of less significance in applications where memory constraints aren’t too critical, but when your applications requires to ensure memory allocations are used well, then Enumerable.Empty is your friend. Personally, I felt Enumerable.Empty should be the “go to” under all circumstances for not only for the reasons described above, but it also is more verbose in declaration and increases code readability manifold.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s