MessagePack 和System.Text.Json 序列化和反序列化性能及对比分析
token 人气:0本博客将测试MessagePack 和System.Text.Json 序列化和反序列化性能
项目文件:
Program.cs代码:
using BenchmarkDotNet.Running; using Demo; var summary = BenchmarkRunner.Run<SerializeTest>();
SerializeTest.cs代码:
using BenchmarkDotNet.Attributes; using MessagePack; using System.Text.Json; namespace Demo { [MemoryDiagnoser, RankColumn, MaxColumn,MinColumn] public class SerializeTest { public List<TestModule> TestDatas = new(); public byte[] Pack; public byte[] Json; public SerializeTest() { for (int i = 0; i < 3000; i++) { var d = new TestModule(Guid.NewGuid(), Guid.NewGuid().ToString("N") + i); d.i = i; TestDatas.Add(d); } Pack = MessagePackSerializer.Serialize(TestDatas, MessagePack.Resolvers.ContractlessStandardResolver.Options); Json = JsonSerializer.SerializeToUtf8Bytes(TestDatas); } [Benchmark] public byte[] GetMessagePackByte() { return MessagePackSerializer.Serialize(TestDatas, MessagePack.Resolvers.ContractlessStandardResolver.Options); } [Benchmark] public byte[] TextJsonByte() { return JsonSerializer.SerializeToUtf8Bytes(TestDatas); } [Benchmark] public List<TestModule> GetMessagePack() { return MessagePackSerializer.Deserialize<List<TestModule>>(Pack, MessagePack.Resolvers.ContractlessStandardResolver.Options); } [Benchmark] public List<TestModule>? TextJson() { return JsonSerializer.Deserialize<List<TestModule>>(Json); } public class TestModule { public TestModule(Guid id, string? value) { Id = id; Value = value; } public Guid Id { get; set; } public int i { get; set; } public string? Value { get; set; } public string MyProperty { get; set; } = "MyProperty"; public string MyProperty1 { get; set; } = "MyProperty"; public string MyProperty2 { get; set; } = "MyProperty"; public string MyProperty3 { get; set; } = "MyProperty"; public string MyProperty4 { get; set; } = "MyProperty"; public string MyProperty5 { get; set; } = "MyProperty"; public string MyProperty6 { get; set; } = "MyProperty"; public string MyProperty7 { get; set; } = "MyProperty"; public string MyProperty8 { get; set; } = "MyProperty"; public string MyProperty9 { get; set; } = "MyProperty"; public string MyProperty10 { get; set; } = "MyProperty"; } } }
然后我们将使用基准测试开始我们的性能测试:
然后测试结束:
我们看到我们的MessagePack的性能在序列化Byte[]的表现对比TextJson上不光是性能比TextJson的更快,内存占用也更小
然后是反序列化对象 MessagePack对比TextJson 性能和内存占用都更强
在使用MessagePack的前提上我配置了MessagePack的配置 MessagePack.Resolvers.ContractlessStandardResolver.Options
如果不加 MessagePack.Resolvers.ContractlessStandardResolver.Options 性能可能并不比Json更快更好 启用了配置以后模型不需要添加特性 并且性能更快
在需要更快性能的场景MessagePack更适合 并且传输的体积更小,所以非常推荐在需要性能的场景下使用MessagePack
顺便我还测试过嵌套序列化和反序列化MessagePack的表现还是比Json的更强
加载全部内容