LINQ到XML中,不断的XDocument装? [英] Linq to Xml, keep XDocument loaded?

查看:158
本文介绍了LINQ到XML中,不断的XDocument装?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我正在做一个WinForms程序,将使用XML文档在幕后作为持久性机制......

Let's say I'm making a WinForms program that will use an XML document behind the scenes as a persistence mechanism...

有哪些优点/缺点,以下两种方法...

What are the pros/cons to the two following approaches...

  1. 加载在每个方法调用中的XDocument:

  1. Load the XDocument in each method call:

public class XmlFoosRepository
{
    string xmlFileName;

    public XmlFoosRepository(string xmlFileName)
    {
        this.xmlFileName = xmlFileName;
    }

    public int AddFoo(Foo foo)
    {
        var xDoc = XDocument.Load(xmlFileName); // Always call Load()

        // ...

        xDoc.Save(xmlFileName);
        return foo.ID;
    }    

    public IEnumerable<Foo> GetFoos()
    {
        var xDoc = XDocument.Load(xmlFileName); // Always call Load()

        // ...

        return foos;
    }
}

  1. 保持的XDocument内存...

  1. Keep the XDocument in memory...

public class XmlFoosRepository
{
    XDocument xDoc;

    public XmlFoosRepository(string xmlFileName)
    {
        xDoc = XDocument.Load(xmlFileName); // Now in memory
    }

    public int AddFoo(Foo foo)
    {
        // ...

        xDoc.Save(xmlFileName);
        return foo.ID;
    }

    public IEnumerable<Foo> GetFoos()
    {
        // ...

        return foos;
    }
}

推荐答案

第一个似乎只是稍微效率低下,因为您每次访问时加载XML文档一无所获。使用选项1,你必须去到磁盘,并加载XML文件到内存中,在访问之前。转到磁盘是最昂贵的操作可以与现代计算机执行的一个,并且应避免尽可能

The first one just seems slightly inefficient as you gain nothing by loading the XML document every time you access it. With option 1 you have to go to disk, and load the XML file into memory, before accessing it. Going to the disk is one of the most costly operations you can perform with a modern computer, and should be avoided as much as possible.

话虽这么说,如果XML文件是大的内存占用是非常显著那么你可能希望只把它加载少量的时间。但是,如果内存占用量是大的,那么你可能要考虑持久化数据,不需要您加载整个文档一次性进行修改以不同的方式。

That being said, if the XML file is that large that the memory footprint is incredibly significant then you may want to only have it loaded for small amounts of time. However, if the memory footprint is that large then you might want to look into a different way of persisting data that doesn't require you to load the whole document at once to make modifications.

这篇关于LINQ到XML中,不断的XDocument装?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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