本博客将测试messagepack 和system.text.json 序列化和反序列化性能
项目文件:
program.cs代码:
using benchmarkdotnet.running; using demo; var summary = benchmarkrunner.run();
serializetest.cs代码:
using benchmarkdotnet.attributes; using messagepack; using system.text.json; namespace demo { [memorydiagnoser, rankcolumn, maxcolumn,mincolumn] public class serializetest { public listtestdatas = 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 getmessagepack() { return messagepackserializer.deserialize >(pack, messagepack.resolvers.contractlessstandardresolver.options); } [benchmark] public list
? textjson() { return jsonserializer.deserialize >(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的更强