Json.NET Performance Tips

Source: Internet
Author: User

Original: http://www.newtonsoft.com/json/help/html/Performance.htm

To keep an application consistently fast, it's important to minimize the amount of time the. NET Framework spends perform ing garbage collection. Allocating too many objects or allocating very large objects can slow down or even halt a application while garbage colle Ction is in progress.

To minimize memory usage and the number of objects allocated, Json.NET supports serializing and deserializing directly to A stream. Reading or writing JSON a piece at a time, instead of have the entire JSON string loaded into memory, is especially impo Rtant when working with JSON documents greater than 85kb in size to avoid the JSON string ending up in the large object he Ap.

New HttpClient (); // read the JSON into a string // string could potentially be very large and cause memory problems string json = client. Getstringasync ("http://www.test.co/large.json"= Jsonconvert.deserializeobject<person> (JSON);
HttpClient client =NewHttpClient (); using(Stream s = client.) Getstreamasync ("Http://www.test.com/large.json"). Result)using(StreamReader sr =NewStreamReader (s))using(Jsonreader reader =NewJsonTextReader (SR)) {Jsonserializer Serializer=NewJsonserializer (); //read the JSON from a stream//json size doesn ' t matter because only a small piece was read at a time from the HTTP requestPerson P = Serializer. Deserialize<person>(reader);}

Passing a jsonconverter to SerializeObject or Deserializeobject provides a simple-to-completely change how an object I s serialized. There is, however, a small amount of overhead; The Canconvert method is called for every value to check whether serialization should was handled by that Jsonconverter.

There is a couple of ways to continue to use jsonconverters without any overhead. The simplest is to specify the jsonconverter using the Jsonconverterattribute. This attribute tells the serializer to always use that converter when serializing and deserializing the type, without the Check.

[Jsonconverter (typeof(Personconverter))] Public classperson{ PublicPerson () {likes=Newlist<string>(); }       Public stringName {Get;Set; }  Publicilist<string> Likes {Get;Private Set; }}

If the class you want to convert not ' t your own and you ' re unable to use an attribute, a jsonconverter can still be used B Y creating your own icontractresolver.

 Public classConvertercontractresolver:defaultcontractresolver { Public New Static ReadOnlyConvertercontractresolver Instance =NewConvertercontractresolver (); protected Overridejsoncontract createcontract (Type objectType) {jsoncontract contract=Base.          Createcontract (ObjectType); //This'll is called once and then cached        if(ObjectType = =typeof(DateTime) | | ObjectType = =typeof(DateTimeOffset)) contract. Converter=NewJavascriptdatetimeconverter (); returncontract; }}

The icontractresolver in the example above would set all datetimes to use the javascriptdateconverter.

Manual serialization

The absolute fastest-to-read and write JSON is-to-use Jsontextreader/jsontextwriter directly to manually serialize Typ Es. Using a reader or writer directly skips any of the overhead from a serializer, such as reflection.

 Public Static stringToJson ( ThisPerson P) {StringWriter SW=NewStringWriter (); JsonTextWriter writer=NewJsonTextWriter (SW); // {writer.    Writestartobject (); //" name": "Jerry"Writer. Writepropertyname ("name"); Writer.    WriteValue (P.name); //"likes": ["Comedy", "Superman"]Writer. Writepropertyname ("likes"); Writer.    Writestartarray (); foreach(stringLikeinchp.likes) {writer.    WriteValue (like); } writer.    Writeendarray (); // }writer.    Writeendobject (); returnSW. ToString ();}

Json.NET Performance Tips

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.