NewtonSoft.Json won a long time ago and we should not be fighting over it anymore. I inherited an old code base which performed serialization to JSON content and deserialization from JSON content using the JavaScriptSerializer - a class that was included in System.Web.Extensions assembly by Microsoft to provide in built support for JSON. What has happened is that JavaScriptSerializer has not been enhanced since its launch and NewtonSoft.Json has made significant improvements in terms of feature and performance. See the comparison sheet. This sheet, alone, should be enough to convince one and all to switch to NewtonSoft.Json. However, I thought of running my own test:
Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(null));
var javaScriptSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var obj = new TypeA() { Name = "Name", Value = "Value" };
var objB = new TypeB() { Name = "Name", Value = "Value" };
Stopwatch watch = new Stopwatch();
watch.Start();
for (int i = 0; i < 100000; i++)
{
var javaScriptSerializer2 = new System.Web.Script.Serialization.JavaScriptSerializer();
string jsonString = javaScriptSerializer2.Serialize( (object)(i % 2 == 0 ? (object)obj : (object)objB));
}
watch.Stop();
Console.WriteLine(watch.ElapsedMilliseconds);
watch.Reset();
watch.Start();
for (int i = 0; i < 100000; i++)
{
string jsonString1 = Newtonsoft.Json.JsonConvert.SerializeObject((object)(i % 2 == 0 ? (object)obj : (object)objB));
}
watch.Stop();
Console.WriteLine(watch.ElapsedMilliseconds);
Results are as expected. Newtonsoft.Json is faster by 50%. Even though the absolute difference is still in milliseconds, Newtonsoft.Json becomes an automatic selection if you add the support for rich CLR types to the kitty.
No comments:
Post a Comment