LINQ到XML中,不断的XDocument装?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 mechanis...

比方说,我正在做一个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...

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

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;
    }
}

保持的XDocument内存...

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.

阅读全文

相关推荐

最新文章