繁体   English   中英

XDocument.Load(XmlReader)表现糟糕;来自Web服务的2 MB XML需要从Stream到解析4秒

[英]XDocument.Load ( XmlReader) has horrible performance; 2 MB XML from Web-Service needs 4 sec from Stream to parse

我正在调用一个webservice,它返回一个大约2MB的xml。

一切都很标准。 问题是创建XDocument。

XDocument xdoc = XDocument.Load( XMLReader Object); // takes 4 sec!!!

我正在创建xdoc,因为我使用LINQ to XML来读取XML。

Stopwatch s = new Stopwatch();

HttpWebRequest req = (HttpWebRequest)WebRequest.Create(MyUri);
System.Net.ServicePointManager.Expect100Continue = false;
req.Method = "POST";

req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = Poststring.Length;

StreamWriter swriter = new StreamWriter(req.GetRequestStream());
swriter.Write(Poststring);
swriter.Close();

s.Start();
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
XmlReader MyXmlReader = null;

XmlReaderSettings settings = new XmlReaderSettings();
settings.ProhibitDtd = false;
settings.ValidationType = ValidationType.None;
settings.ConformanceLevel = ConformanceLevel.Document;

Stream stream = response.GetResponseStream();
s.Stop(); 
Debug.WriteLine("stream= response.GetResponseStream(): " + s.ElapsedMilliseconds);
s.Reset();

MyXmlReader = XmlReader.Create(stream, settings);

Debug.WriteLine("Before XDocument.Load(MyXmlReader): " + s.ElapsedMilliseconds);
s.Start();
XDocument xdoc = XDocument.Load(MyXmlReader);
s.Stop();
Debug.WriteLine("Duration: " + s.ElapsedMilliseconds);

PC已有2年历史,4 GB RAM。 电脑还可以。 我在其他2台PC和笔记本电脑上测试了它并获得了相同的结果。 我创建XDocument xdoc的方式需要很长时间,但为什么呢?

我测试过了

XDocument xdoc = XDocument.Load(String with path to the same xmlFile on my pc);

花了20毫秒。

编辑:这里有一些时间:

stream= response.GetResponseStream(): 5276 Milliseconds

我想这是从服务器到我的电脑的时间

持续时间:4855

所需时间: XDocument xdoc = XDocument.Load(MyXmlReader);

也许是一个问题因为它正在将流程“转换”为XDocument xdoc对象?

edit2:我刚刚测试过

HttpWebResponse response = (HttpWebResponse)req.GetResponse();
MemoryStream ms = new MemoryStream();

//responsetime from server to my pc: 6000 ms
Stream stream = response.GetResponseStream(); 
stream.CopyTo(ms); //this operation takes 4000 ms!!!
ms.Position = 0;
XDocument x4 = XDocument.Load(ms);// this takes 13 ms!!!

将流对象中的数据转换为一些有用的数据(如字符串或ms)需要很长时间,但为什么呢?

我是对的,来自Web服务的所有数据都是100%发送并且已经到达,只有下一行代码才能执行? 或者是stream.copyTo(ms)在打开并仍在接收数据的流上运行?

在线:

MyXmlReader = XmlReader.Create(stream, settings);

您正在读取Stream ,它本质上是一个管道 ,而不是一个 ; 流尚未拥有所有数据。 我猜测2MB需要大约4秒才能到达线路。

如果时间太长,请确保已在http连接上启用了gzip / deflate。 正如oberfreak指出的那样,还有其他数据格式更适合大型文档(xml在大尺寸时可能会变得难以操作,尽管它通常会起作用)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM