c# - Jon Skeet 的 Edulinq - 空数组缓存

标签 c# caching

我正在研究 Jon Skeet 的 Edulinq,我看到了以下代码,第 23 页,他在其中为 Linq 的 Empty() 运算符实现了缓存机制

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

我的问题是,这实际上是如何缓存 Array 变量的?

可选,它在 CLR 中如何工作?

编辑:在此之后,他还提到有人反对返回数组。为什么任何人都不应该返回一个数组(即使它的大小为 0?)?

最佳答案

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

CLR 根据类型参数缓存它。基本上,EmptyHolder<int>是与 EmptyHolder<string> 不同的类型等等,并且类型初始值设定项被调用(自动,由 CLR)每个具体类型。

所以:

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?

恐怕这是我不太了解的实现细节。但基本上,这就是关于 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?)?

嗯,有评论:

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

我个人认为这不是问题,但编写替代实现很有趣 :)

关于c# - Jon Skeet 的 Edulinq - 空数组缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14733786/

相关文章:

c# - Web 服务拒绝访问

c# - 主机启动时间比预期长 - Azure 函数

c++ - 避免与 1 :N relationship in entity-component-system 相关的缓存未命中

java - 2 种方式与谷歌日历/Outlook 同步

c# - 适用于 Windows XP 的 visual studio 2013 安装程序

caching - 浏览器后退按钮不执行 Controller 方法

java - 如何从EhCache获取初始数据快照

android - 使用改造缓存特定响应

web-applications - HTML5 离线模式和地理定位

c# - 是否有将单个项目添加到 IEnumerable<T> 的 Linq 方法?