缓存 IEnumerable [英] Caching IEnumerable

查看:15
本文介绍了缓存 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆