Here’s a tip to get the better performance when sending xml to a WCF web service from Silverlight or WPF…
Never send or return xml as a string. Anytime you pass around a string data type as a parameter to your service or send back a string return value, the string will be XML encoded. Imagine, the following string:
<hello/> (8 bytes)
this is really sent around as:
<hello/> (14 bytes)
Something that should have taken only 8 bytes of your bandwidth, took almost double that. Now an extra 6 bytes isn’t bad, but you can see how it wouldn’t take long for your xml to quickly inflate the overall size of the request or response and at some point even have a noticable delay for the usability of your app.
Fortunately, the solution is simple! Use an System.Linq.Xml.XElement object instead. By doing so, WCF is smart enough to encode your xml right in the message envelope as pure xml. Furthermore, if you need to work with that xml on the receiving end, it’s already in an object type more suitable for most purposes than a String.
To demonstrate and prove what is happening, I wrote a test app that sent a test parameter to a service as a String, XElement and byte array. The test data being sent in all three cases was the xml: <test/>. Then I used fiddler2 web debugging proxy to see what was actually sent to the server. Check out below what I saw:
Sending a String:
Sending a byte array:
Sending an XElement:
XElement wins! 🙂 And just to be sure, I also confirmed that responses for the three data types produced identical results.
A note about compression
Compression does not completely remove the benefit of sending as XElement. Besides the fact that server compression only works on responses, it doesn’t eliminate the benefit from sending xml without encoding. This was surprising to me. I thought that compressing my responses on the server would find common xml encoding phrases like “<” and “>” and find a way to turn them into single bytes using a mapping technique and make an xml encoded and non-xml encoded response virtually identical in size when compressed. To test my assumption, I ran a test where I took a big xml file, and added it and an encoded version of it in a zip file. Here was my result:
Acording Although encoded xml can be compressed at a slightly higher compression ratio, it was not as dramatic as I thought and suggests and the final compressed sizes show that although compression on the server helps reduce the size of your response a great deal, xml encoded strings will still be larger than necessary. Check out my previous blog post to find out more about opimizing responses by turning on server compression.