最近在研究web api 2,看了一篇文章,講解如何提高性能的,html
在序列化速度的跑分中,Protobuf一騎絕塵,序列化速度快,性能強,體積小,因此打算了解下這個利器git
1:安裝篇github
谷歌官方沒有提供.net的實現,因此在nuget上找了一個移植的web
Nuget裏搜索Protobuf-net,下載,自動添加到項目中api
2:定義數據結構數據結構
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:封裝簡單操做類性能
按照做者使用習慣,簡單提供了一個Helper類測試
using System.IO; using System.Text; using ProtoBuf; namespace ConsoleApplication1 { public class ProtobufHelper { /// <summary> /// 序列化 /// </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<T>(ms, t); return Encoding.UTF8.GetString(ms.ToArray()); } } /// <summary> /// 反序列化 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="content"></param> /// <returns></returns> public static T DeSerialize<T>(string content) { using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(content))) { T t = Serializer.Deserialize<T>(ms); return t; } } } }
4:操做體驗spa
代碼很簡單,就不分開貼了.net
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 = "八百里開外", Address = new Address { Line1 = "Line1", Line2 = "Line2" } }; var p2 = new Person { Id = 2, Name = "一槍", 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); //寫入文件 File.WriteAllText("D://hello.txt", content); Console.WriteLine("\r\n****解析部分*****"); List<Person> pResult = ProtobufHelper.DeSerialize<List<Person>>(content); foreach (Person p in pResult) { Console.WriteLine(p.Name); } Console.Read(); } } }
控制檯運行結果
一樣的數據,和Json所佔用空間對比,高下立判
本章代碼下載:猛擊我
若是提示沒有protobuf,請查看第一步前往nuget下載
後記
protobuf雖然有千般好,可是咱們是在 web api上使用的,前臺js解析不了Protobuf,因此只能用Json咯~!
StackService雖然Github上有2K多個Star,可是收費的。。一樣的事情web api 2也能作到,因此也略過它。
最終做者選擇了跑分測試裏面的第二名Jil https://github.com/kevin-montrose/Jil