【发布时间】:2014-07-23 07:36:52
【问题描述】:
我尝试在已经存在的 xml 文件中添加行节点,并在其中添加平均 (100'000 行)。 一切正常,但它真的很慢..我不知道为什么。我必须停止我的程序,因为它已经 10 分钟了,还没有完成^^。
我使用 Xdocument 类添加节点和 XmlTextWriter 因为我需要搜索具有属性的后代节点(区域)并在添加节点之后。
非常感谢
这是我的 xmlFile
<World>
<Matrix>
<Regions>
<Region id="0" min="x:0;y:0;z:0" max="x:256;y:16;z:256">
<Structures type="cube" >
</Structures>
</Region>
<Region id="1" min="x:256;y:0;z:0" max="x:512;y:16;z:256">
<Structures type="cube" >
</Structures>
</Region>
<Region id="2" min="x:512;y:0;z:0" max="x:768;y:16;z:256">
<Structures type="cube" >
</Structures>
</Region>
// till Region id="512" ...
以及我用来插入新节点的代码
更新:使用 StringBuilder 提高内存使用率 像 @threeFx 一样给我建议
// Loop 100'000 times in a recursive method ...
// Search the good node
var reg = arcadia.xDocumentWorld.Descendants("Region").FirstOrDefault(s => s.Attribute("id").Value == region.Index.ToString());
var struc = reg.Element("Structures");
//string posMin = "x:"+ node_.CubeNode.BoundingBox.Min.X+";y:"+ node_.CubeNode.BoundingBox.Min.Y+"z:"+ node_.CubeNode.BoundingBox.Min.Z;
//string posMax = "x:"+ node_.CubeNode.BoundingBox.Max.X+";y:"+ node_.CubeNode.BoundingBox.Max.Y+"z:"+ node_.CubeNode.BoundingBox.Max.Z;
var sbMin = new StringBuilder();
var sbMax = new StringBuilder();
sbMin.Append("x:");
sbMin.Append(node_.CubeNode.BoundingBox.Min.X);
sbMin.Append("y:");
sbMin.Append(node_.CubeNode.BoundingBox.Min.Y);
sbMin.Append("z:");
sbMin.Append(node_.CubeNode.BoundingBox.Min.Z);
sbMax.Append("x:");
sbMax.Append(node_.CubeNode.BoundingBox.Max.X);
sbMax.Append("y:");
sbMax.Append(node_.CubeNode.BoundingBox.Max.Y);
sbMax.Append("z:");
sbMax.Append(node_.CubeNode.BoundingBox.Max.Z);
var cube = new XElement("Cube", new XAttribute("id", node_.ItemGroup),
new XAttribute("min", sbMin.ToString()),
new XAttribute("max", sbMax.ToString()));
//Add the new cube node
struc.Add(cube);
//Dispose the StringBuilder
sbMin.Clear();
sbMax.Clear();
正如我现在通过测试分析性能看到的那样,.Net Linq [List.FirstOrDefault] 花费了很多性能..
var reg = arcadia.xDocumentWorld.Descendants("Region").FirstOrDefault(s => s.Attribute("id").Value == region.Index.ToString());
【问题讨论】:
-
缩小范围:您是否尝试过分析(使用较小的数据集)您的程序以查看热点在哪里?
-
我刚刚完成了一个基本的性能测试并放了一张图片。我现在打算用 CLR Profiler 做另一个测试来检查内存 GC。
标签: c# .net xml linq-to-xml