Recently in the study of Web API 2, read an article explaining how to improve performance,
In the running of the serialization speed, Protobuf a ride dust, fast serialization, high performance, small size, so intend to understand the next tool
1: Installation article
Google officially did not provide the implementation of. net, so a transplant was found on NuGet
NuGet Search protobuf-net, download, automatically add to project
2: Defining data structures
Using Protobuf;namespace consoleapplication1{ [protocontract] class person { [protomember (1)] public int Id {get; set;} [protomember (2)] public string Name {get; set;} [protomember (3)] Public address address {get; set;} } [protocontract] Class Address { [protomember (1)] public string Line1 {get; set;} [protomember (2)] public string Line2 {get; set;}} }
3: Encapsulation Simple Operation class
In accordance with the Author's habits, a simple helper class is provided
Using system.io;using system.text;using protobuf;namespace consoleapplication1{public class Protobufhelper {/ <summary>//serialization///</summary>/<typeparam name= "T" ></typeparam>/ <param name= "t" ></param>///<returns></returns> public static string serialize< T> (t-t) {using (memorystream ms = new MemoryStream ()) {SERIALIZER.SERIALIZE&L T T> (ms, t); return Encoding.UTF8.GetString (ms. ToArray ()); }}///<summary>//deserialization///</summary>//<typeparam name= "T" ></typ Eparam>//<param name= "content" ></param>///<returns></returns> public STA Tic T deserialize<t> (string content) {using (memorystream ms = new MemoryStream (Encoding.UTF8.GetBy TES (content)) {t t = serializer.deSerialize<t> (ms); Return t; } } }}
4: Operation Experience
The code is simple, it's not Separate.
Using system;using system.collections.generic;using system.io;namespace consoleapplication1{class Program { static void Main (string[] Args) {var p1 = new person {Id = 1, Name = "800 miles away", address = new address {Line1 = "Line1", Line2 = "Line2"}; var p2 = new Person {Id = 2, Name = "one shot", address = new address {Line1 = "Flat Line1", Line2 = "Flat Line2"} }; list<person> Psource = new list<person> () {p1, p2}; String content = Protobufhelper.serialize<list<person>> (psource); Console.Write (content); Write file File.writealltext ("d://hello.txt", content); Console.WriteLine ("\ r \ nParsing PART * * * * *; list<person> PResult = protobufhelper.deserialize<list<person>> (content); foreach (person p in PResult) {console.writeline (p.name); } console.read (); } }}
Console Run Results
The same data, compared to the space occupied by json, stands
Postscript
Protobuf Although there are thousands of good, but we are in the Web API used, The front desk JS can not parse protobuf, so only with JSON ~ ~!
Stackservice Although there are more than 2K star on github, It's Charged. The same thing Web API 2 can do, so also skip it.
The final author chooses the second Jil in the test run Https://github.com/kevin-montrose/Jil
1. With very minimal annotation in the class level
// Only required on the class level class personentity{ publicstringgetset;} public string Get Set ; }}
2. Without any annotation (using Runtimetypemodel)
Static voidinitializeprotobufruntime () {varAssembly = assembly.getassembly (typeof(plainentities.personentity)); varTypes =assembly. GetTypes (); foreach(varTinchTypes. Where (x = X.namespace.contains ("plainentities")) {console.writeline ("processing {0}", t.fullname); varMeta = RuntimeTypeModel.Default.Add (t,false); varindex =1; //find any derived class for the entity foreach(varDinchTypes. Where (x =x.issubclassof (t))) { vari = index++; Console.WriteLine ("\tsubtype: {0}-#{1}", d.name, i); Meta. Addsubtype (i, d); } //then Add the Properties foreach(varPinchT.getproperties (bindingflags.instance | BindingFlags.Public | Bindingflags.declaredonly). Where (x = X.getsetmethod ()! =NULL)) { vari = index++; Console.WriteLine ("\tproperty: {0}-#{1}", p.name, i); Meta. AddField (i, p.name); } }}
And both the above works quite well without any performance differences.
------------------
TestBinaryEntities
------------------
Process: 100000 items, MemorySize: 7400705, Completed in: 3877 ms, Serialization took: 676 ms, Deserialization took: 2948 ms
----------------------------------
Testprotobuffullyannotatedentities
----------------------------------
process:100000 items, memorysize:3983490, completed in:682 ms, serialization took:164 ms, deserialization took:253 ms
-------------------------------------
testprotobufimplicitannotatedentities
----------- --------------------------
process:100000 items, memorysize:3983490, completed in:595 ms, serialization took:104 ms, deserialization took:210 ms
-------------------------------
TestProtobufRuntimeRegistration
-------------------------------
Processing ProtobufTestConsole.PlainEntities.BaseEntity
Subtype: PersonEntity - #1
Property: Id - #2
Property: Gender - #3
Processing ProtobufTestConsole.PlainEntities.PersonEntity
Property: FirstName - #1
Property: LastName - #2
Property: Age - #3
Process: 100000 items, MemorySize: 4083490, Completed in: 646 ms, Serialization took: 113 ms, Deserialization took: 232 ms
Looking forward to get:)
Also attached the sample project for reference
[go] serialization Titans protobuf-net, Getting started with hands-on transcripts