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


基础教程推荐
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 将 XML 转换为通用列表 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- rabbitmq 的 REST API 2022-01-01