本部落格將測試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的更強
技術分享群:737776595
來自 token的分享