[转]序列化悍将Protobuf-Net,入门动手实录
最近在研究web api 2,看了一篇文章,讲解如何提升性能的,

在序列化速度的跑分中,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虽然有千般好,但是我们是在 web api上使用的,前台js解析不了Protobuf,所以只能用Json咯~!
StackService虽然Github上有2K多个Star,但是收费的。。同样的事情web api 2也能做到,所以也略过它。
最终作者选择了跑分测试里面的第二名Jil https://github.com/kevin-montrose/Jil
1. With very minimal annotation on the class level
[ProtoContract(ImplicitFields = ImplicitFields.AllPublic)] // only required on the class level
class PersonEntity
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
2. Without any annotation (using RuntimeTypeModel)
static void InitializeProtobufRunTime()
{
var assembly = Assembly.GetAssembly(typeof(PlainEntities.PersonEntity));
var types = assembly.GetTypes();
foreach (var t in types.Where(x => x.Namespace.Contains("PlainEntities")))
{
Console.WriteLine("Processing {0}", t.FullName);
var meta = RuntimeTypeModel.Default.Add(t, false);
var index = ; // find any derived class for the entity
foreach (var d in types.Where(x => x.IsSubclassOf(t)))
{
var i = index++;
Console.WriteLine("\tSubtype: {0} - #{1}", d.Name, i);
meta.AddSubType(i, d);
} // then add the properties
foreach (var p in t.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly).Where(x => x.GetSetMethod() != null))
{
var i = 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 this in :)
Also attached the sample project for reference
[转]序列化悍将Protobuf-Net,入门动手实录的更多相关文章
- 序列化悍将Protobuf-Net,入门动手实录
最近在研究web api 2,看了一篇文章,讲解如何提升性能的, 在序列化速度的跑分中,Protobuf一骑绝尘,序列化速度快,性能强,体积小,所以打算了解下这个利器 1:安装篇 谷歌官方没有提供.n ...
- 速度最快的Json序列框架Jil,入门动手实录
好吧,我又先要贴出跑分图了,出处 Jil是一个面向Json的序列化框架,在Nuget上可以下载到 支持数据类型 值得一提的是,Guid指定带破折号格式(44B2673B-B5CA-477B-A8EA- ...
- 序列化悍将Protobuf-Net
序列化悍将Protobuf-Net,入门动手实录 最近在研究web api 2,看了一篇文章,讲解如何提升性能的, 在序列化速度的跑分中,Protobuf一骑绝尘,序列化速度快,性能强,体积小,所以打 ...
- 最快的序列化组件protobuf的.net版本protobuf.net
Protobuf是google开源的一个项目,用户数据序列化反序列化,google声称google的数据通信都是用该序列化方法.它比xml格式要少的多,甚至比二进制数据格式也小的多. Prot ...
- 数据序列化之protobuf
数据序列化之protobuf 很多时候需要将一些数据打包,就是把这些数据搞在一起,方便处理.最常见的情况就是把需要传输的数据,当然数据不止一条,打包成一个消息,然后发送出去,接收端再以一定的规则接收并 ...
- 序列化之protobuf与avro对比(Java)
最近在做socket通信中用到了关于序列化工具选型的问题,在调研过程中开始趋向于用protobuf,可以省去了编解码的过程.能够实现快速开发,且只需要维护一份协议文件即可. 但是调研过程中发现了pro ...
- 重点关注之自定义序列化方式(Protobuf和Msgpack)
除了默认的JSON和XML序列化器外,如果想使用其它格式的(比如二进制)序列化器,也是可以的.比如著名的Protobuf和Msgpack,它们都是二进制的序列化器,特点是速度快,体积小.使用方法如下. ...
- Protobuf学习 - 入门
古之立大事者,不惟有超世之才,亦必有坚忍不拔之志 -- 苏轼·<晁错论> 从公司的项目源码中看到了这个东西,觉得挺好用的,写篇博客做下小总结.下面的操作以C++为编程语言,protoc的版 ...
- Protobuf 从入门到实战
简介 从第一次接触Protobuf到实际使用已经有半年多,刚开始可能被它的名字所唬住,其实就它是一种轻便高效的数据格式,平台无关.语言无关.可扩展,可用于通讯协议和数据存储等领域. 优点 平台无关,语 ...
随机推荐
- protobuf中文教程(第一篇)
声明:本文大部分内容翻译自官方英文文档,其中可能穿插着加入自己的语言用以辅助理解,本文禁止转载. 一.什么是protocol buffers Protocol buffers是一个灵活的.高效的.自动 ...
- VS2015 调试Web项目 遭遇 HTTP 错误 500.23 - Internal Server Error
此错误是因为项目使用的托管管道模式有问题,将集成改为传统即可 选中项目 进入项目属性 ,如图界面
- Bubble Cup 8 finals C. Party (575C)
题意: 给定n个人,分两天晚上去夜总会开派对,要求每天恰好有n/2个人去,且每人去的夜总会各不相同. 每个人对不同的晚上不同的夜总会有不同的满意度,求一个方案使得所有人的满意度之和最大. 夜总会数量= ...
- 耗时两月,NHibernate系列出炉
写在前面 这篇总结本来是昨天要写的,可昨天大学班长来视察工作,多喝了点,回来就倒头就睡了,也就把这篇总结的文章拖到了今天. nhibernate系列从开始着手写,到现在前后耗费大概两个月的时间,通过总 ...
- 移动开发框架剖析(二) Hammer专业的手势控制
浏览器底层并没有给元素提供类似,单击,双击,滑动,拖动这些直接可以用的控制接口,一切的手势动作都只能通过模拟出来.移动端浏览器唯一给我们提供的就只是mousedown -> mousemove ...
- XUnit - Shared Context between Tests
原文 单元测试类通常都会有share setup和cleanup的相关代码.xUnit.net根据共享的范围提供了几种share setup和cleanup的方法. Constructor and D ...
- pycharm快捷键及一些常用设置
pycharm快捷键及一些常用设置,有需要的朋友可以参考下. Alt+Enter 自动添加包 Ctrl+t SVN更新 Ctrl+k SVN提交 Ctrl + / 注释(取消注释)选择的行 Ctrl+ ...
- css负边距之详解
自从1998年CSS2作为推荐以来,表格的使用渐渐退去,成为历史.正因为此,从那以后CSS布局成为了优雅代码的代名词. 对于所有设计师使用过的CSS概念,负边距作为最少讨论到的定位方式要记上一功.这就 ...
- MySQL 优化数据库对象
一.考虑是用 procedure analyse() 函数对当前应用的表进行分析.字段类型是否可优化. 二.通过拆分提高表的访问效率. (A) 针对MyISAM表,有两种拆分方法: 垂直拆分:主码和某 ...
- html 标签
CSS : overflow : hidden -- 就是给一个盒子定义了一个显示范围.内部的物体.只有在这个范围内部才会被显示.不然就被隐藏. overflow-x overflow-y 控制 ...