在服务与服务之间传输的是二进制数据,而在此之前有多种方法将数据内容进行序列化来减小数据传递大小,现针对于目前主流的几种序列化方式做了简单数据统计对比。
先做下简单介绍↓↓↓
1、protobuf-net
protobuf-net is a contract based serializer for .NET code, that happens to write data in the "protocol buffers" serialization format engineered by Google. The API, however, is very different to Google's, and follows typical .NET patterns (it is broadly comparable, in usage, to XmlSerializer, DataContractSerializer, etc). It should work for most .NET languages that write standard types and can use attributes.
GitHub地址:https://github.com/mgravell/protobuf-net
2、Newtonsoft.Json(Json.Net)
Json.NET is a personal open source project. Started in 2006, thousands of hours have been invested in refining and tuning Json.NET with the goal of making it not just the best JSON serializer for .NET but the best serializer for any computer language.
官网:https://www.newtonsoft.com/json
3、DataContractSerializer
Use the DataContractSerializer class to serialize and deserialize instances of a type into an XML stream or document. For example, you can create a type named Person with properties that contain essential data, such as a name and address. You can then create and manipulate an instance of the Person class and write all of its property values in an XML document for later retrieval, or in an XML stream for immediate transport. Most important, the DataContractSerializer is used to serialize and deserialize data sent in Windows Communication Foundation (WCF) messages. Apply the DataContractAttribute attribute to classes, and the DataMemberAttribute attribute to class members to specify properties and fields that are serialized.
现对于这三种序列化方式从序列化后数据大小、序列化耗时、反序列化耗时进行统计对比。
版本:protobuf-net-2.3.2.0、Newtonsoft.Json-6.0.4
统计代码:
class Program
{
static void Main(string[] args)
{
Console.WriteLine();
Console.WriteLine("****************第一次测试****************");
Console.WriteLine();
TestMain();
Console.WriteLine();
Console.WriteLine("****************第二次测试****************");
Console.WriteLine();
TestMain();
Console.WriteLine();
Console.WriteLine("****************第三次测试****************");
Console.WriteLine();
TestMain();
Console.Read();
} #region Private private static void TestMain(int count)
{
var list = GetList(count); var pbSerializeTime = 0.00;
var pbDeSerializeTime = 0.00; var jsonSerializeTime = 0.00;
var jsonDeSerializeTime = 0.00; var dataContractSerializeTime = 0.00;
var dataContractDeSerializeTime = 0.00; Console.WriteLine(); //protobuf-net
Console.WriteLine("---------------protobuf-net--------------");
Stopwatch watch = new Stopwatch();
watch.Start();
var pbResult = ProtobufSerialize(list);
File.WriteAllText($@"D:\Code\WCF数据压缩传输\WcfTest{DateTime.Now.ToString("yyyyMMddHHmmss")}.txt", pbResult);
watch.Stop(); pbSerializeTime = watch.ElapsedMilliseconds;
Console.WriteLine();
Console.WriteLine($"序列化后数据大小:{HumanReadableFilesize(pbResult.Length)}");
Console.WriteLine();
Console.WriteLine($"序列化耗时:{watch.ElapsedMilliseconds} 毫秒");
Console.WriteLine(); watch = new Stopwatch();
watch.Start();
var pbValue = ProtobufDeSerialize<List<TransmissionModel>>(pbResult);
watch.Stop();
pbDeSerializeTime = watch.ElapsedMilliseconds;
Console.WriteLine($"反序列化耗时:{watch.ElapsedMilliseconds} 毫秒");
Console.WriteLine(); Console.WriteLine($"反序列化结果验证:{pbValue[0].Name}:{!string.IsNullOrWhiteSpace(pbValue[0].Name)}");
Console.WriteLine(); //Newtonsoft.Json
Console.WriteLine("---------------Newtonsoft.Json--------------");
Console.WriteLine();
watch = new Stopwatch();
watch.Start();
var jsonResult = Newtonsoft.Json.JsonConvert.SerializeObject(list);
File.WriteAllText($@"D:\Code\WCF数据压缩传输\WcfTest{DateTime.Now.AddSeconds(1).ToString("yyyyMMddHHmmss")}.txt", jsonResult);
watch.Stop();
jsonSerializeTime = watch.ElapsedMilliseconds;
Console.WriteLine($"序列化后数据大小:{HumanReadableFilesize(jsonResult.Length)}");
Console.WriteLine();
Console.WriteLine($"序列化耗时:{watch.ElapsedMilliseconds} 毫秒");
Console.WriteLine(); watch = new Stopwatch();
watch.Start();
var jsonValue = Newtonsoft.Json.JsonConvert.DeserializeObject<List<TransmissionModel>>(jsonResult);
watch.Stop();
jsonDeSerializeTime = watch.ElapsedMilliseconds;
Console.WriteLine($"反序列化耗时:{watch.ElapsedMilliseconds} 毫秒");
Console.WriteLine(); Console.WriteLine($"反序列化结果验证:{jsonValue[0].Name}:{!string.IsNullOrWhiteSpace(jsonValue[0].Name)}");
Console.WriteLine(); //DataContractSerializer
Console.WriteLine("---------------DataContractSerializer--------------");
Console.WriteLine(); watch = new Stopwatch();
watch.Start();
var dataContractFileName = $@"D:\Code\WCF数据压缩传输\WcfTest{DateTime.Now.AddSeconds(2).ToString("yyyyMMddHHmmss")}.txt";
var dataContractSerializer = new DataContractSerializer(typeof(List<TransmissionModel>));
var dataContractfi = new FileInfo(dataContractFileName);
using (var stream = dataContractfi.Create())
{
dataContractSerializer.WriteObject(stream, list);
}
watch.Stop();
dataContractSerializeTime = watch.ElapsedMilliseconds;
Console.WriteLine($"序列化后数据大小:{HumanReadableFilesize(dataContractfi.Length)}");
Console.WriteLine();
Console.WriteLine($"序列化耗时:{watch.ElapsedMilliseconds} 毫秒");
Console.WriteLine(); watch = new Stopwatch();
watch.Start();
var dataContractValue = new List<TransmissionModel>();
DataContractSerializer serializer = new DataContractSerializer(typeof(List<TransmissionModel>));
using (FileStream fs = new FileStream(dataContractFileName, FileMode.Open, FileAccess.Read))
{
using (XmlReader reader = new XmlTextReader(dataContractFileName, fs))
{
dataContractValue = (List<TransmissionModel>)serializer.ReadObject(reader);
}
}
watch.Stop();
dataContractDeSerializeTime = watch.ElapsedMilliseconds;
Console.WriteLine($"反序列化耗时:{watch.ElapsedMilliseconds} 毫秒");
Console.WriteLine();
Console.WriteLine($"反序列化结果验证:{dataContractValue[0].Name}:{!string.IsNullOrWhiteSpace(dataContractValue[0].Name)}"); //统计结果
Console.WriteLine();
Console.WriteLine($"=====================统计结果======================");
Console.WriteLine();
Console.WriteLine($"protobuf-net序列化后数据大小为Newtonsoft.Json的 {Math.Round(pbResult.Length / Convert.ToDouble(jsonResult.Length), 2) * 100}%,为DataContractSerializer的 {Math.Round(pbResult.Length / Convert.ToDouble(dataContractfi.Length), 2) * 100}%");
Console.WriteLine();
Console.WriteLine($"protobuf-net序列化耗时为Newtonsoft.Json的 {Math.Round(pbSerializeTime / jsonSerializeTime, 2) * 100}%,为DataContractSerializer的 {Math.Round(pbSerializeTime / dataContractSerializeTime, 2) * 100}%");
Console.WriteLine();
Console.WriteLine($"protobuf-net反序列耗时为Newtonsoft.Json的 {Math.Round(pbDeSerializeTime / jsonDeSerializeTime, 2) * 100}%,为DataContractSerializer的 {Math.Round(pbDeSerializeTime / dataContractDeSerializeTime, 2) * 100}%");
Console.WriteLine();
} private static List<TransmissionModel> GetList(int count)
{
var list = new List<TransmissionModel>();
var model1 = new TransmissionModel() { ID = , Name = "我爱北京*", TempModel = new TempModel() { Age = , Name = "*上有毛爷爷" } };
var model2 = new TransmissionModel() { ID = , Name = "*上红旗飘", TempModel = new TempModel() { Age = , Name = "I Love 毛爷爷" } };
for (int i = ; i < count; i++)
{
list.Add(model1);
list.Add(model2);
}
return list;
} private static string ProtobufSerialize<T>(T obj)
{
using (var memory = new MemoryStream())
{
Serializer.Serialize(memory, obj);
return Encoding.UTF8.GetString(memory.ToArray());
}
} /// <summary>
/// 反序列化
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="content"></param>
/// <returns></returns>
private static T ProtobufDeSerialize<T>(string content)
{
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(content)))
{
T t = Serializer.Deserialize<T>(ms);
return t;
}
} /// <summary>
/// 转换方法
/// </summary>
/// <param name="size">字节值</param>
/// <returns></returns>
private static String HumanReadableFilesize(double size)
{
String[] units = new String[] { "B", "KB", "MB", "GB", "TB", "PB" };
double mod = 1024.0;
int i = ;
while (size >= mod)
{
size /= mod;
i++;
}
return Math.Round(size) + units[i];
}
#endregion
} [DataContract]
[ProtoContract]
class TransmissionModel
{
[DataMember]
[ProtoMember()]
public int ID { get; set; } [DataMember]
[ProtoMember()]
public string Name { get; set; } [DataMember]
[ProtoMember()]
public TempModel TempModel { get; set; }
} [DataContract]
[ProtoContract]
class TempModel
{
[DataMember]
[ProtoMember()]
public int Age { get; set; } [DataMember]
[ProtoMember()]
public string Name { get; set; }
}
测试统计结果如下:
****************第一次测试**************** ---------------protobuf-net-------------- 序列化后数据大小:27KB 序列化耗时: 毫秒 反序列化耗时: 毫秒 反序列化结果验证:我爱北京*:True ---------------Newtonsoft.Json-------------- 序列化后数据大小:65KB 序列化耗时: 毫秒 反序列化耗时: 毫秒 反序列化结果验证:我爱北京*:True ---------------DataContractSerializer-------------- 序列化后数据大小:148KB 序列化耗时: 毫秒 反序列化耗时: 毫秒 反序列化结果验证:我爱北京*:True =====================统计结果====================== protobuf-net序列化后数据大小为Newtonsoft.Json的 %,为DataContractSerializer的 % protobuf-net序列化耗时为Newtonsoft.Json的 %,为DataContractSerializer的 % protobuf-net反序列耗时为Newtonsoft.Json的 %,为DataContractSerializer的 % ****************第二次测试**************** ---------------protobuf-net-------------- 序列化后数据大小:273KB 序列化耗时: 毫秒 反序列化耗时: 毫秒 反序列化结果验证:我爱北京*:True ---------------Newtonsoft.Json-------------- 序列化后数据大小:654KB 序列化耗时: 毫秒 反序列化耗时: 毫秒 反序列化结果验证:我爱北京*:True ---------------DataContractSerializer-------------- 序列化后数据大小:1MB 序列化耗时: 毫秒 反序列化耗时: 毫秒 反序列化结果验证:我爱北京*:True =====================统计结果====================== protobuf-net序列化后数据大小为Newtonsoft.Json的 %,为DataContractSerializer的 % protobuf-net序列化耗时为Newtonsoft.Json的 %,为DataContractSerializer的 % protobuf-net反序列耗时为Newtonsoft.Json的 %,为DataContractSerializer的 % ****************第三次测试**************** ---------------protobuf-net-------------- 序列化后数据大小:3MB 序列化耗时: 毫秒 反序列化耗时: 毫秒 反序列化结果验证:我爱北京*:True ---------------Newtonsoft.Json-------------- 序列化后数据大小:6MB 序列化耗时: 毫秒 反序列化耗时: 毫秒 反序列化结果验证:我爱北京*:True ---------------DataContractSerializer-------------- 序列化后数据大小:14MB 序列化耗时: 毫秒 反序列化耗时: 毫秒 反序列化结果验证:我爱北京*:True =====================统计结果====================== protobuf-net序列化后数据大小为Newtonsoft.Json的 %,为DataContractSerializer的 % protobuf-net序列化耗时为Newtonsoft.Json的 %,为DataContractSerializer的 % protobuf-net反序列耗时为Newtonsoft.Json的 %,为DataContractSerializer的 %
各序列化生成文件内容对比:
protobuf-net:
Newtonsoft.Json:
DataContractSerializer:
综合分析:
1、数据内容格式及大小:DataContractSerializer(序列化为XML)> Newtonsoft.Json(序列化为Json文本) > protobuf-net(暂未知格式) ,protobuf-net 表现最优,protobuf-net序列化后数据大小为Newtonsoft.Json的 42%,为DataContractSerializer的 19%。
2、序列化耗时最小方面:随着数据本身大小的变化各序列化耗时之间的排名有不同变化,表现较好的主要为 DataContractSerializer 和 protobuf-net ,三轮测试下来 Newtonsoft.Json 明显比其它两种序列化方式耗时长(详细查看上方测试统计数据)。
3、反序列耗时最小方面:随着数据本身大小的变化排名也有不同变化,表现最好的为protobuf-net(详细查看上方测试统计数据)。
客观结论:
通过对比序列化后数据大小、序列化耗时、反序列化耗时、数据格式得出客观结论:protobuf-net 在整体效率上来说最优。
关于 protobuf-net 的具体应用将会在下篇文章写出。
以上仅为个人测试统计对比,欢迎提出建议指正。
本文参考文章:http://www.cnblogs.com/onlytiancai/archive/2009/07/02/protobuf_net_test.html
↓↓↓欢迎关注我的公众号