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
基础教程推荐
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- WPF 模态进度窗口 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
