views:

352

answers:

1

I'm using the following lines of code to read the response of an asynchronous HttpWebRequest. This seems to be the largest amount of time spent in a particular operation. Is there anything I can optimize here?

System.Net.HttpWebResponse oResp =(System.Net.HttpWebResponse)oReq.EndGetResponse(oResult);
oResp = (HttpWebResponse)oReq.GetResponse();
StreamReader oStreamReader = new StreamReader(oResp.GetResponseStream());
string sResponse = oStreamReader.ReadToEnd();

...goes on to make an XmlDocument, append some more XML to it, then perform an XSL transform.

Creating the Connections:

HttpWebRequest oReq;
oReq = (HttpWebRequest)WebRequest.Create(sUrl + sQueryString);
oReq.ContentType = sContentType;
oReq.Method = "POST";
oReq.ContentLength = aBytes.Length;
Stream oStream = oReq.GetRequestStream();
oStream.Write(aBytes, 0, aBytes.Length);
oStream.Close();
AsyncState oState = new AsyncState(oReq);
return oReq.BeginGetResponse(fCallBack, oState);
A: 

I found one major improvement to the scheme I was using. Rather than using the StreamReader and ReadToEnd to get the Stream into a string, only then to convert it into an XmlDocument. I skipped the middle man and converted the Stream directly into a XmlDocument.

This left me with another problem though, I had to change the parent of the XmlDocument to fit my Xslt (there are a great many and they all expect the structure I had). See http://stackoverflow.com/questions/2269150/how-can-i-add-new-root-element-to-a-c-xmldocument for that fix.

This has given me a roughly 2/3 decrease in the time taken to process the results of the webservice call, and a great decrease in the amount of memory used. In the previous version, the response xml was in memory two different times (maybe three if the stream counts)!

In addition, removing the extra GetResponse seemed to help.

using (HttpWebResponse oResp = (HttpWebResponse)oReq.EndGetResponse(oResult))
{
oXml.Load(oResp.GetResponseStream());
XmlNode oApiResult = oXml.RemoveChild(oXml.DocumentElement);
oXml.LoadXml(sOtherXml);
oXml.DocumentElement.AppendChild(oApiResult);
}
aepheus