If I create a list of XElements from an XDocument, is this a new copy of the list of elements created in memory?
If I have XDocument
it loaded into memory from XDocument.Load
and then I make a LINQ-XML query on it, like this:
XDocument doc = XDocument.Load(@"C:/doc.xml");
var orders = doc.Root.Element("Envelope").Elements("Order");
Is there a copy in memory IEnumerable<XElement>
returned by the second line? Or is it just a background copy of the originalXDocument
What if I actually listed it by calling .ToList()
?
XDocument.Load
will read the entire dataset into memory.
Data queries return links to existing items. For example, check the original source for GetElement , which is the yield
existing nodes for the caller directly (by reference).
The main additional memory created when a document is requested will be the memory needed to implement the iterators themselves, which should be extremely small compared to the size of the document.
Just a link.
You will need to use an operator new
to allocate memory to a new one List<XElement>
on the heap.
Is there an in memory copy of IEnumerable returned by the second string? Or is it just a reference copy of the original XDocument
As others have pointed out, its the last one.
If you need a Deep Clone of an element, you can use the constructor XElement
:
var ordersCopy = doc.Root.Element("Envelope").Elements("Order").Select(element => new XElement(element);