在序列化速度的跑分中,Protobuf一骑绝尘,序列化速度快,性能强,体积小,所以打算了解下这个利器
1:安装篇
谷歌官方没有提供.net的实现,所以在nuget上找了一个移植的
Nuget里搜索Protobuf-net,下载,自动添加到项目中
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:操作体验
代码很简单,就不分开贴了
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下载
跑分测试里面第二名JIL https://github.com/kevin-montrose/Jil