Friday, October 23, 2009

Json Serialization

I've currently been experimenting with performance tuning some REST services.  I was surprised how easy it was to change XML serialisation to Json serialisation.  Just a simply matter of changing System.Xml.Serialization.XmlSerializer to System.Runtime.Serialization.Json.DataContractJsonSerializer.

Seems to be about 30% smaller in size over xml.

            using (var stream1 = new MemoryStream()) {
                var serializer = new DataContractJsonSerializer(dto.GetType());
                serializer.WriteObject(stream1, dto);
                stream1.Position = 0;
                var reader = new StreamReader(stream1);
                return reader.ReadToEnd();

            using (var stream2 = new MemoryStream(Encoding.Unicode.GetBytes(serialisedInstance)) {
                var ser = new DataContractJsonSerializer(type);
                return ser.ReadObject(stream2);

Size comparison:

    <Country>New Zealand</Country>
    <Line1>24 Rodney Street</Line1>
499 bytes.

{"City":"Auckland","Country":"New Zealand","CreatedOn":"\/Date(951735600000+1300)\/","Id":"36322616-0b72-45b4-aa51-4e7119103f27","Line1":"24 Rodney Street","Line2":"","Sid":"36322616-0b72-45b4-aa51-4e7119103f27@AddressDto","State":"Auckland","Suburb":"Birkenhead","Updated":"\/Date(1199040119000+1300)\/","Version":"36322616-0b72-45b4-aa51-4e7119103f27","Zip":"2801"}
367 bytes.

Performance Testing:
I've done a comparison of this Xml to Json change and now have some hard data on how much smaller and faster Json is.

The test involves calling a REST service to first check for a randomly created string LogOnId availability; this is a HTTP GET call. LogOnId must be unique and a user may choose their preferred handle. After the uniqueness check comes back successful, it calls a create client service call. This is a HTTP POST. Finally it calls GET to return the newly created client.

Each call is time individually. 10 threads will be used to create 1,000 new clients. The REST service has been configured to use an in-memory database to minimuse random Database and network delays. All up 10,000 clients should be created.

The test creating the 10,000 clients for Xml and Json were repeated 3 times each to give an average.

No comments:

Post a Comment