protocolbuffer(以下简称PB)是google 的一种数据交换的格式,它独立于语言,独立于平台。google 提供了多种语言的实现:java、c#、c++、go 和 python,每一种实现都包含了相应语言的编译器以及库文件。由于它是一种二进制的格式,比使用 xml 进行数据交换快许多。可以把它用于分布式应用之间的数据通信或者异构环境下的数据交换。作为一种效率和兼容性都很优秀的二进制数据传输格式,可以用于诸如网络传输、配置文件、数据存储等诸多领域。
protobuf与json的性能对比是选择它的原因。
下面来看一下:
static void Main(string[] args)
{
int[] a = { 1000, 10000, 100000, 1000000 };
for (int j = 0; j < a.Length; j++)
{
Console.WriteLine("---------------------------------------------");
ProtoBufMethod(a[j]);
JsonMethod(a[j]);
}
}
public static DateTime GetDateTime(string timeStamp)
{
DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
long lTime = long.Parse(timeStamp);
TimeSpan toNow = new TimeSpan(lTime);
DateTime targetDt = dtStart.Add(toNow);
return dtStart.Add(toNow);
}
public static void JsonMethod(int count)
{
List<Person> ap = new List<Person>();
for (int i = 0; i < count; i++)
{
Random r = new Random();
Person a = new Person();
a.Id = i + "_" + r.Next();
a.Name = "Test" + i;
a.Sex = 1;
a.MinZu = 1;
a.Address = "Beijing Haidian Zhongguancun";
ap.Add(a);
}
DateTime begintime = GetDateTime( DateTime.Now.Ticks.ToString());
string result = JsonConvert.SerializeObject(ap);
DateTime endtime = GetDateTime(DateTime.Now.Ticks.ToString());
long rr = (long)(endtime - begintime).TotalMilliseconds;
Console.WriteLine("Json:"+count+"个耗费时间(毫秒):"+rr);
byte[] data = System.Text.Encoding.Default.GetBytes(result);
FileStream f = File.Create(String.Format("D:\json_{0}.txt",count));
f.Write(data, 0, data.Length);
f.Flush();
f.Close();
}
public static void ProtoBufMethod(int count)
{
List<Person> ap = new List<Person>();
for (int i = 0; i < count; i++)
{
Random r = new Random();
Person a = new Person();
a.Id = i + "_" + r.Next();
a.Name = "Test" + i;
a.Sex = 1;
a.MinZu = 1;
a.Address = "Beijing Haidian Zhongguancun";
ap.Add(a);
}
DateTime begintime = GetDateTime(DateTime.Now.Ticks.ToString());
MemoryStream ms = new MemoryStream();
Serializer.Serialize<List<Person>>(ms, ap);
DateTime endtime = GetDateTime(DateTime.Now.Ticks.ToString());
long rr = (long)(endtime - begintime).TotalMilliseconds;
Console.WriteLine("ProtoBuf:" + count + "个耗费时间(毫秒):" + rr);
byte[] b = ms.ToArray();
FileStream f = File.Create(String.Format("D:\protobuf_{0}.txt",count));
f.Write(b, 0, b.Length);
f.Flush();
f.Close();
}
通过在对实例化对象进行1000,10000,100000,1000000次的序列化对比发现结果如下:
由此可见:protobuf在序列化方面比json耗费的时间少了一半还多,同时生成的文件的大小也小了一半。但是二者在序列化对象的数量上,有个共同点:在数量是10000时性能最佳,耗费的时间最短。
最后
以上就是鲜艳玫瑰最近收集整理的关于C#中Protobuf实用指南与性能对比的全部内容,更多相关C#中Protobuf实用指南与性能对比内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复