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...
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;
}
}
or
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;
}
}
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With