How to improve JSON deserialization speed in .Net? (JSON.net or other?)

前端 未结 4 1446
旧巷少年郎
旧巷少年郎 2020-12-12 21:11

We\'re considering replacing (some or many) \'classic\' SOAP XML WCF calls by JSON (WCF or other) calls, because of the lower overhead and ease of use directly in Javascript

4条回答
  •  时光取名叫无心
    2020-12-12 21:55

    I'm adding 2 more points here, which help me to improve my IoT application performance. I was receiving millions of JSON messages every day.

    1. Changes in ContractResolver instance

    Old code

    return JsonConvert.SerializeObject(this, Formatting.Indented,
                              new JsonSerializerSettings
                              {
                                  ContractResolver = new CamelCasePropertyNamesContractResolver()
                              });
    

    New Code

    Not creating contract resolver instance on every call, Instead using a single instance

    return JsonConvert.SerializeObject(this, Formatting.Indented,
                              new JsonSerializerSettings
                              {
                                  ContractResolver = AppConfiguration.CamelCaseResolver
                              });
    
    1. Avoid creating JObject

    Old Code

    JObject eventObj = JObject.Parse(jsonMessage);
    eventObj.Add("AssetType", assetType); //modify object
    
    JObject eventObj2 = JObject.Parse(jsonMessage);
    eventObj.Add("id", id); //modify object
    

    NewCode

    JObject eventObj = JObject.Parse(jsonMessage);
    eventObj.Add("AssetType", assetType); //modify object
    
    JObject eventObj2 = (JObject)eventObj.DeepClone();
    eventObj.Add("id", id); //modify object
    

    To check performance benefits, I used benchmarkdotnet to see the difference. check this link as well.

提交回复
热议问题