Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jon Skeet's Edulinq - Empty Array Caching

Tags:

c#

caching

I was going through Edulinq by Jon Skeet, and I came across the following code, Page 23, in which he implements cache mechanism for Empty() operator of Linq

private static class EmptyHolder<T>
{
   internal static readonly T[] Array = new T[0];
}

My question is, how does this actually cache the Array variable?

Optionally, How does it work in CLR?

Edit: Also following that, he mentions there was a revolt against returning an array. Why should anybody not return an array (even if it is 0 sized?)?

like image 812
Aniket Inge Avatar asked Feb 06 '13 16:02

Aniket Inge


1 Answers

My question is, how does this actually cache the Array variable?

The CLR caches it per type argument. Basically, EmptyHolder<int> is a different type to EmptyHolder<string> etc, and the type initializer is invoked (automatically, by the CLR) once per concrete type.

So:

var x = EmptyHolder<string>.Array; // Needs to construct the empty string[] array
var y = EmptyHolder<string>.Array; // No extra work! x and y have the same value
var z = EmptyHolder<int>.Array; // This constructs an empty array for int[]

Optionally, How does it work in CLR?

That's an implementation detail that I don't know much about, I'm afraid. But basically this is all about how the CLR does things :)

Edit: Also following that, he mentions there was a revolt against returning an array. Why should anybody not return an array (even if it is 0 sized?)?

Well, there was a comment of:

The array method is not so great: People will incorrectly depend on the return value being an array although this is not documented.

Personally I don't think it's an issue, but it was fun to write the alternative implementation :)

like image 150
Jon Skeet Avatar answered Sep 23 '22 20:09

Jon Skeet