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.
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.
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).
The returned IEnumerable<> might be empty, but it will never be null .
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With