缓存IEnumerable [英] Caching IEnumerable

查看:90
本文介绍了缓存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.

因此,作为一项性能改进:

So, as a performance improvement:

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.

是否有中间条件可以让我获得回报,直到整个列表都被迭代,然后将其缓存并为后续请求提供缓存?

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天全站免登陆