Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is better, Enumerable.Empty<T> or new[0]?

Tags:

c#

These are the same:

IEnumerable<string> i;
i = Enumerable.Empty<string>();
i = new string[0];

So, which to use?

I think the first communicates intent more clearly, but it is bigger and a bit noisier, not to mention ugly in the debugger. The second is also more efficient in memory and CPU, if I'm reading Reflector right.

I'm leaning towards the new type[0], but wanted to know what you all think.

like image 595
scobi Avatar asked Mar 16 '11 01:03

scobi


People also ask

What is enumerable empty?

IEnumerable<T> Enumerable. Empty<T>(); From MSDN: The Empty(TResult)() method caches an empty sequence of type TResult . When the object it returns is enumerated, it yields no elements.

How do I return empty IEnumerable?

Empty<T> actually returns an empty array of T (T[0]), with the advantage that the same empty array is reused. Note that this approach is not ideal for non-empty arrays, because the elements can be modified (however an array can't be resized, resizing involves creating a new instance).

Can IEnumerable be null?

The returned IEnumerable<> might be empty, but it will never be null .


3 Answers

Enumerable.Empty<T> caches the creation of the empty array, so the same array will be always be returned, while the second statement creates a new array with each call.

I would tend to Enumerable.Empty<T>, as it shows the intention of the programmer more clearly, and also because using an explicit array creation because of memory usage is premature optimization in a managed program, as the runtime will almost always allocate more than necessary memory to the process anyway.

like image 78
Femaref Avatar answered Oct 17 '22 09:10

Femaref


The difference in terms of performance/memory usage is incredibly negligible in this situation, so that would not be my deciding factor.

I would personally use Enumerable.Empty, mainly because it very clearly describes the developer intent.

like image 30
Reed Copsey Avatar answered Oct 17 '22 11:10

Reed Copsey


It looks to me like Enumerable.Empty delegates to EmptyEnumerable which returns an array of length 0. But it returns the same one every time, and keeps that empty array alive forever.

like image 41
Ben Voigt Avatar answered Oct 17 '22 10:10

Ben Voigt