深度比較常見庫中序列化和反序列化效能的效能差異

百寶門園地發表於2023-09-18

背景和目的

本文介紹了幾個常用的序列化和反序列化庫,包括System.Text.Json、Newtonsoft.Json、 Protobuf-Net、MessagePack-Net,我們將對這些庫進行效能測評

庫名稱 介紹 Github地址
System.Text.Json .NET Core 3.0及以上版本的內建JSON庫,用於讀寫JSON文字。它提供了高效能和低分配的功能。 System.Text.Json
Newtonsoft.Json 也被稱為Json.NET,是.NET中最常用的JSON序列化庫之一。它提供了靈活的方式來轉換.NET物件為JSON字串,以及將JSON字串轉換為.NET物件。 Newtonsoft.Json
Protobuf-Net .NET版本的Google's Protocol Buffers序列化庫。Protocol Buffers是一種語言中立、平臺中立、可擴充套件的序列化結構資料的方法。 Protobuf-Net
MessagePack-Net MessagePack是一個高效的二進位制序列化格式,它允許你在JSON-like的格式中交換資料,但是更小、更快、更簡單。 MessagePack-Net

效能測試

測評電腦配置

元件 規格
CPU 11th Gen Intel(R) Core(TM) i5-11320H
記憶體 40 GB DDR4 3200MHz
作業系統 Microsoft Windows 10 專業版
電源選項 已設定為高效能
軟體 LINQPad 7.8.5 Beta
執行時 .NET 7.0.10

準備工作

0、匯入Nuget包

1、Bogus(34.0.2)
2、MessagePack(2.5.124)
3、Newtonsoft.Json(13.0.3)
4、protobuf-net(3.2.26)
5、System.Reactive(6.0.0)

1、效能測試函式

IObservable<object> Measure(Action action, int times = 5)
{
	return Enumerable.Range(1, times).Select(i =>
	{
		var sw = Stopwatch.StartNew();

		long memory1 = GC.GetTotalMemory(true);
		long allocate1 = GC.GetTotalAllocatedBytes(true);
		{
			action();
		}
		long allocate2 = GC.GetTotalAllocatedBytes(true);
		long memory2 = GC.GetTotalMemory(true);

		sw.Stop();
		return new
		{
			次數 = i,
			分配記憶體 = (allocate2 - allocate1).ToString("N0"),
			記憶體提高 = (memory2 - memory1).ToString("N0"),
			耗時 = sw.ElapsedMilliseconds,
		};
	}).ToObservable();
}

這個測量函式的它的作用

多次執行指定的動作,並測量每次執行該動作時的記憶體分配和執行時間。

然後,對於每次操作,它建立並返回一個新的匿名物件,該物件包含以下屬性:

次數:操作的次數。
分配記憶體:操作期間分配的記憶體量(操作結束後的已分配位元組減去操作開始前的已分配位元組)。
記憶體提高:操作期間記憶體的增加量(操作結束後的總記憶體減去操作開始前的總記憶體)。
耗時:操作的執行時間(以毫秒為單位)。

2、生成隨機資料的函式

IEnumerable<User> WriteData()
{
	var data = new Bogus.Faker<User>()
		.RuleFor(x => x.Id, x => x.IndexFaker + 1)
		.RuleFor(x => x.Gender, x => x.Person.Gender)
		.RuleFor(x => x.FirstName, (x, u) => x.Name.FirstName(u.Gender))
		.RuleFor(x => x.LastName, (x, u) => x.Name.LastName(u.Gender))
		.RuleFor(x => x.Email, (x, u) => x.Internet.Email(u.FirstName, u.LastName))
		.RuleFor(x => x.BirthDate, x => x.Person.DateOfBirth)
		.RuleFor(x => x.Company, x => x.Person.Company.Name)
		.RuleFor(x => x.Phone, x => x.Person.Phone)
		.RuleFor(x => x.Website, x => x.Person.Website)
		.RuleFor(x => x.SSN, x => x.Person.Ssn())
		.GenerateForever().Take(6_0000);
	return data;
}

Bogus 是一個非常有用的 C# 庫,它可以幫助你生成偽造的資料,或者說“假資料”。這在測試或開發階段非常有用,你可以使用它來填充資料庫,或者在沒有實際使用者資料的情況下測試應用程式。

如果想詳細瞭解使用請參考 這篇文章https://www.cnblogs.com/sdflysha/p/20190821-generate-lorem-data.html

3、資料實體類

[MessagePackObject, ProtoContract]
public class User
{
    [Key(0), ProtoMember(1)]
    public int Id { get; set; }

    [Key(1), ProtoMember(2)]
    public int Gender { get; set; }

    [Key(2), ProtoMember(3)]
    public string FirstName { get; set; }

    [Key(3), ProtoMember(4)]
    public string LastName { get; set; }

    [Key(4), ProtoMember(5)]
    public string Email { get; set; }

    [Key(5), ProtoMember(6)]
    public DateTime BirthDate { get; set; }

    [Key(6), ProtoMember(7)]
    public string Company { get; set; }

    [Key(7), ProtoMember(8)]
    public string Phone { get; set; }

    [Key(8), ProtoMember(9)]
    public string Website { get; set; }

    [Key(9), ProtoMember(10)]
    public string SSN { get; set; }
}

開始效能測試

以下測試程式碼會加入寫入檔案,以模擬真實的使用場景,效能怎麼樣

1、System.Text.Json 效能測試

序列化測試程式碼

void TextJsonWrite()
{
	var data = WriteData();

	Measure(() =>
		{
			string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "test-data1.json");
			using var file = File.Create(path);
			System.Text.Json.JsonSerializer.Serialize(file,data);
		})
	.Dump();
}

檔案大小:14.3MB

測試結果

次數 分配記憶體 記憶體提高 耗時
1 1,429,688,200 67,392 2494
2 1,429,960,352 320 2610
3 1,429,596,256 8 2615
4 1,430,126,504 -64 2753
5 1,429,549,184 -432 2918

反序列化測試程式碼

void TextJsonRead()
{
	Measure(() =>
	{
		string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "test-data1.json");
		byte[] bytes = File.ReadAllBytes(path);
		System.Text.Json.JsonSerializer.Deserialize<List<User>>(bytes);
	}).Dump();
}

測試結果

次數 分配記憶體 記憶體提高 耗時
1 42,958,536 43,728 212
2 43,093,448 48 185
3 42,884,408 24 120
4 42,883,312 24 129
5 43,100,896 24 117

2、Newtonsoft.Json 效能測試

序列化測試程式碼

void JsonNetWrite()
{
	var data = WriteData();

	Measure(() =>
	{
		string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "test-data2.json");
		var jsonData = Newtonsoft.Json.JsonConvert.SerializeObject(data);
		File.WriteAllText(path, jsonData);
	})
	.Dump();
}

檔案大小:14.3MB

測試結果

次數 分配記憶體 記憶體提高 耗時
1 1,494,035,696 42,608 2196
2 1,494,176,144 320 2289
3 1,494,684,672 -24 2899
4 1,494,292,376 2,152 3393
5 1,495,260,472 64 3499

反序列化測試程式碼

void JsonNetRead()
{
	Measure(() =>
	{
		string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "test-data2.json");
		var jsonData = File.ReadAllText(path);
		var data = Newtonsoft.Json.JsonConvert.DeserializeObject<List<User>>(jsonData);
	})
	.Dump();
}

測試結果

次數 分配記憶體 記憶體提高 耗時
1 92,556,920 63,216 275
2 92,659,784 48 314
3 92,407,736 24 245
4 92,616,912 24 276
5 92,416,128 24 305

3、ProtobufNet 效能測試

序列化測試程式碼

void ProtobufNetWrite()
{
	var data = WriteDataTwo();
	Measure(() =>
	{
		string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "test-data3.bin");
		using var file = File.Create(path);
		Serializer.Serialize(file, data);
	}).Dump();
}

檔案大小:7.71MB

測試結果

次數 分配記憶體 記憶體提高 耗時
1 712,168 163,512 170
2 6,760 -192 111
3 7,040 280 97
4 6,760 24 66
5 244,200 0 68

反序列化測試程式碼

void ProtobufNetRead()
{
	Measure(() =>
	{
		string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "test-data3.bin");
		using var file = File.OpenRead(path);
		Serializer.Deserialize<List<UserProtobuf>>(file);
	}
	).Dump();
}

測試結果

次數 分配記憶體 記憶體提高 耗時
1 29,485,888 1,084,240 113
2 28,242,856 48 96
3 28,340,672 24 85
4 28,333,088 24 80
5 28,242,856 24 76

4、MessagePack-Net 效能測試

序列化測試程式碼

void MessagePackNetWrite()
{
	var data = WriteDataThreee();
	Measure(() =>
	{
		string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "UserMessagePackData.bin");
		using var file = File.Create(path);
	   	MessagePackSerializer.Serialize(file, data);
	}).Dump();
}

檔案大小:7.21MB

測試結果

次數 分配記憶體 記憶體提高 耗時
1 80,552 9,512 52
2 7,432 24 46
3 7,432 24 45
4 120,400 -1,072 46
5 7,432 24 48

反序列化測試程式碼

void MessagePackNetRead()
{
	Measure(() =>
	{
		string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "UserMessagePackData.bin");
		byte[] bytes = File.ReadAllBytes(path);
		MessagePackSerializer.Deserialize<List<UserMessagePack>>(bytes);
	}).Dump();
}

測試結果

次數 分配記憶體 記憶體提高 耗時
1 35,804,728 24 82
2 35,804,728 24 65
3 35,804,728 24 56
4 35,804,728 32 66
5 35,806,248 848 80

結論

序列化效能測試結果

效能測試名稱 分配記憶體平均數 (bytes) 耗時平均數 (ms) 檔案大小 (MB) 分配記憶體百分比 (%) 耗時百分比 (%) 檔案大小百分比 (%)
Newtonsoft.Json 1,494,489,872 2,855 14.3 100 100 100
System.Text.Json 1,429,784,099 2,678 14.3 95 93.8 100
ProtobufNet 195,385 102 7.71 0.013 3.5 53.9
MessagePack-Net 44,649 47 7.21 0.0029 1.6 50.4

反序列化效能測試結果

效能測試名稱 分配記憶體平均數 (bytes) 耗時平均數 (ms) 分配記憶體百分比 (%) 耗時百分比 (%)
Newtonsoft.Json 92,531,496 283 100 100
System.Text.Json 42,807,420 152 46.2 54.7
ProtobufNet 28,529,072 90 30.8 31.8
MessagePack-Net 35,805,032 69 38.6 24.3

注:

1、 分配記憶體比例、耗時比例和檔案大小比例都以 Newtonsoft.Json 的數值為基準,計算出的百分比表示在相比於 Newtonsoft.Json 的表現。
2、 分配記憶體平均數、耗時平均數是透過將給定的五次測試結果取平均值得出的。
3、 檔案大小是由測試程式碼生成的檔案大小,計算出的百分比表示在相比於 Newtonsoft.Json 的表現。

基於上述表格,我們可以得出以下結論:

  1. 記憶體分配:在記憶體分配方面,ProtobufNet 和 MessagePack-Net 顯著優於 System.Text.Json 和 Newtonsoft.Json。它們的記憶體分配僅為 Newtonsoft.Json 的 0.01% 和 0.003%,這表明它們在處理大資料時的記憶體效率非常高。

  2. 耗時:在耗時方面,ProtobufNet 和 MessagePack-Net 也表現出超過其他兩個庫的效能。ProtobufNet 的耗時為 Newtonsoft.Json 的 3.6%,而 MessagePack-Net 的耗時僅為 2.1%。這意味著它們在處理大量資料時的速度非常快。

  3. 檔案大小:在生成的檔案大小方面,ProtobufNet 和 MessagePack-Net 的檔案大小明顯小於 System.Text.Json 和 Newtonsoft.Json。ProtobufNet 和 MessagePack-Net 的檔案大小分別為 Newtonsoft.Json 檔案大小的 53.9% 和 50.4%。這說明它們的序列化效率更高,能夠生成更小的檔案。

  4. System.Text.Json vs Newtonsoft.Json:在比較這兩個庫時,System.Text.Json 在記憶體分配和耗時方面都稍微優於 Newtonsoft.Json,但差距不大。在檔案大小方面,它們的表現相同。

綜上所述,如果考慮記憶體分配、處理速度和檔案大小,ProtobufNet 和 MessagePack-Net 的效能明顯優於 System.Text.Json 和 Newtonsoft.Json。

5、總結

基於上面的資料,個人一些看法,雖然我們平常用的是Newtonsoft.Json,但瞭解一些其他一些比較好的庫的使用可以擴充套件視野,本次測試的庫雖然加入了寫入檔案這方面的因素,但對效能影響不是很大,本以為ProtobufNet已經是效能最好的了,但上面的測試結果,顯然 MessagePack-Net 效能最好,還有一個意外發現,針對NetCore 6.0,新出的庫System.Text.Json效能比Newtonsoft.Json好5%

作者 => 百寶門瞿佑明

原文地址:https://blog.baibaomen.com/深度比較常見庫中序列化和反序列化效能的效能差/

相關文章