17

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.

scobi
  • 14,252
  • 13
  • 80
  • 114

3 Answers3

27

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.

Femaref
  • 60,705
  • 7
  • 138
  • 176
8

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.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
5

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.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720