Atomización previa de objetos XName (LINQ to XML)
Una manera de mejorar el rendimiento en LINQ to XML es realizar una atomización previa de los objetos XName. La atomización previa significa que se asigna una cadena a un objeto XName antes de crear el árbol XML mediante los constructores de las clases XElement y XAttribute. A continuación, en lugar de pasar una cadena al constructor, que utilizaría la conversión implícita de cadena a XName, pasa el objeto XName inicializado.
Esto mejora el rendimiento al crear un árbol XML de gran tamaño en el que se repiten nombres. Para ello, debe declarar e inicializar los objetos XName antes de construir el árbol XML y, a continuación, utilizar los objetos XName en lugar de especificar las cadenas para los nombres de atributo y elemento. Esta técnica puede dar lugar a un aumento considerable del rendimiento si se va a crear un gran número de elementos o atributos con el mismo nombre.
Debería probar la atomización previa con su situación para decidir si debe utilizarla.
Ejemplo: Creación de elementos de varias maneras, con y sin atomización previa
En el siguiente ejemplo se muestra la atomización previa.
XName Root = "Root";
XName Data = "Data";
XName ID = "ID";
XElement root = new XElement(Root,
new XElement(Data,
new XAttribute(ID, "1"),
"4,100,000"),
new XElement(Data,
new XAttribute(ID, "2"),
"3,700,000"),
new XElement(Data,
new XAttribute(ID, "3"),
"1,150,000")
);
Console.WriteLine(root);
Dim root1 As XName = "Root"
Dim data As XName = "Data"
Dim id As XName = "ID"
Dim root2 As New XElement(root1, New XElement(data, New XAttribute(id, "1"), "4,100,000"),
New XElement(data, New XAttribute(id, "2"), "3,700,000"),
New XElement(data, New XAttribute(id, "3"), "1,150,000"))
Console.WriteLine(root2)
Este ejemplo produce el siguiente resultado:
<Root>
<Data ID="1">4,100,000</Data>
<Data ID="2">3,700,000</Data>
<Data ID="3">1,150,000</Data>
</Root>
En el siguiente ejemplo se muestra la misma técnica en un documento XML que se encuentra en un espacio de nombres:
XNamespace aw = "http://www.adventure-works.com";
XName Root = aw + "Root";
XName Data = aw + "Data";
XName ID = "ID";
XElement root = new XElement(Root,
new XAttribute(XNamespace.Xmlns + "aw", aw),
new XElement(Data,
new XAttribute(ID, "1"),
"4,100,000"),
new XElement(Data,
new XAttribute(ID, "2"),
"3,700,000"),
new XElement(Data,
new XAttribute(ID, "3"),
"1,150,000")
);
Console.WriteLine(root);
Dim aw As XNamespace = "http://www.adventure-works.com"
Dim root1 As XName = aw + "Root"
Dim data As XName = aw + "Data"
Dim id As XName = "ID"
Dim root2 As New XElement(root1, New XAttribute(XNamespace.Xmlns + "aw", aw),
New XElement(data, New XAttribute(id, "1"), "4,100,000"),
New XElement(data, New XAttribute(id, "2"), "3,700,000"),
New XElement(data, New XAttribute(id, "3"), "1,150,000"))
Console.WriteLine(root2)
Este ejemplo produce el siguiente resultado:
<aw:Root xmlns:aw="http://www.adventure-works.com">
<aw:Data ID="1">4,100,000</aw:Data>
<aw:Data ID="2">3,700,000</aw:Data>
<aw:Data ID="3">1,150,000</aw:Data>
</aw:Root>
El ejemplo siguiente es más similar a lo que probablemente encontrará en el mundo real. En este ejemplo, una consulta proporciona el contenido del elemento:
XName Root = "Root";
XName Data = "Data";
XName ID = "ID";
DateTime t1 = DateTime.Now;
XElement root = new XElement(Root,
from i in System.Linq.Enumerable.Range(1, 100000)
select new XElement(Data,
new XAttribute(ID, i),
i * 5)
);
DateTime t2 = DateTime.Now;
Console.WriteLine("Time to construct:{0}", t2 - t1);
Dim root1 As XName = "Root"
Dim data As XName = "Data"
Dim id As XName = "ID"
Dim sw As Stopwatch = Stopwatch.StartNew()
Dim root2 As New XElement(root1, From i In Enumerable.Range(1, 100000)
Select New XElement(data, New XAttribute(ID, i), i * 5))
sw.Stop()
Console.WriteLine($"Time to construct: {sw.ElapsedMilliseconds} milliseconds")
El ejemplo anterior rinde más que el siguiente, en el que los nombres no se atomizan previamente:
DateTime t1 = DateTime.Now;
XElement root = new XElement("Root",
from i in System.Linq.Enumerable.Range(1, 100000)
select new XElement("Data",
new XAttribute("ID", i),
i * 5)
);
DateTime t2 = DateTime.Now;
Console.WriteLine("Time to construct:{0}", t2 - t1);
Dim sw As Stopwatch = Stopwatch.StartNew()
Dim root As New XElement("Root", From i In Enumerable.Range(1, 100000)
Select New XElement("Data", New XAttribute("ID", i), i * 5))
sw.Stop()
Console.WriteLine($"Time to construct: {sw.ElapsedMilliseconds} milliseconds")