Caching IEnumerable(缓存 IEnumerable)
问题描述
public IEnumerable<ModuleData> ListModules()
{
foreach (XElement m in Source.Descendants("Module"))
{
yield return new ModuleData(m.Element("ModuleID").Value);
}
}
最初,上面的代码很棒,因为如果不需要,就不需要评估整个集合.
Initially the above code is great since there is no need to evaluate the entire collection if it is not needed.
然而,一旦所有模块都被枚举一次,在没有变化的情况下重复查询 XDocument 变得更加昂贵.
However, once all the Modules have been enumerated once, it becomes more expensive to repeatedly query the XDocument when there is no change.
因此,作为性能改进:
public IEnumerable<ModuleData> ListModules()
{
if (Modules == null)
{
Modules = new List<ModuleData>();
foreach (XElement m in Source.Descendants("Module"))
{
Modules.Add(new ModuleData(m.Element("ModuleID").Value, 1, 1));
}
}
return Modules;
}
如果我重复使用整个列表,这很好,但在其他情况下就不那么好了.
Which is great if I am repeatedly using the entire list but not so great otherwise.
是否有一个中间地带,我可以在整个列表被迭代之前产生 return,然后缓存它并将缓存提供给后续请求?
Is there a middle ground where I can yield return until the entire list has been iterated, then cache it and serve the cache to subsequent requests?
推荐答案
你可以看看保存枚举器的状态,它描述了如何创建惰性列表(它会缓存一次迭代的项目).
You can look at Saving the State of Enumerators which describes how to create lazy list (which caches once iterated items).
这篇关于缓存 IEnumerable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:缓存 IEnumerable


基础教程推荐
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01