Reduce the XML WCF response size

I recently received a request for a post on how to reduce the XML response size of a WCF service easily. When developing for mobile devices (like the iPhone), it’s crucial to keep loading times as small as possible. Reducing the size of the XML response can be done in two ways: either the actual data or the encapsulating XML elements is/are treated. Changing the actual data probably has a severe impact on you’re applications inner workings, that’s why we’ll focus on the latter. Here’s how:

[DataContract(Name = "p")]
public class Product
{
   [DataMember(Name = "n")]
   public string Name { get; set; }
 
   [DataMember(Name = "a")]
   public int Amount { get; set; }
}

By adding the name attribute we can specify how the XML element will be called, by default it uses the name of the class or property. The original response is 64 characters long, while the tweaked is only 35 characters, a reduction in size of more than 40%. This also works when the response is or contains a list or products.

// Original response
<Product>
   <Name>MacBook</Name>
   <Amount>123</Amount>
</Product>
 
// Response after tweaking
<p>
   <n>MacBook</n>
   <a>123</a>
<p>

In the end it’s a trade-off between overall readability and performance, if you’re consuming the service in .NET with WCF, then you won’t even know that the response has been tampered with, since it’s all done in the background. If you’re calling the WCF service from for instance Objective-C and are parsing the result, you’ll have to adjust the parsing to use the new XML element names.

In the case of an application for a mobile device, the benefits (faster loading) outweigh the disadvantages. You even get an added bonus: less bandwidth consumption on the server.

Tags: , ,

Leave a Reply