網站首頁 編程語言 正文
利用GZip和Brotli壓縮方法的優勢,減少字符串數據的大小,提高.NET核心應用程序的性能。
在開發應用程序時,你經常需要處理字符串。由于字符串對象在性能方面的成本很高,你經常想壓縮你的字符串內容,即字符串對象中的數據,以減少有效載荷。有幾個庫可以做到這一點,但兩個流行的技術是GZip和Brotli。
在這篇文章中,我們將討論如何在C#中使用GZip和Brotli算法對字符串進行壓縮和解壓。要使用這里提供的代碼示例,你的系統中應該安裝有Visual Studio 2022。如果你還沒有副本,你可以在這里下載Visual Studio 2022。
在Visual Studio 2022中創建一個控制臺應用程序項目
首先,讓我們在Visual Studio中創建一個.NET Core控制臺應用程序項目。假設你的系統中已經安裝了Visual Studio 2022,按照下面的步驟創建一個新的.NET Core控制臺應用程序項目:
- 啟動Visual Studio IDE。
- 點擊 "創建一個新項目"。
- 在 "創建一個新項目 "窗口中,從顯示的模板列表中選擇 "控制臺應用程序"。
- 點擊 "下一步"。
- 在接下來顯示的 "配置你的新項目 "窗口中,指定新項目的名稱和位置。
- 在 "其他信息 "窗口中,選擇.NET 6.0作為運行時間,然后點擊下一步。
- 點擊 "創建"。
我們將使用這個項目來說明下面的字符串壓縮和解壓縮。但首先我們要安裝一個基準測試包BenchmarkDotNet,它將使我們能夠衡量我們從壓縮中獲得的好處。
安裝BenchmarkDotNet NuGet包
基準測試代碼對于了解你的應用程序的性能至關重要。在這篇文章中,我們將利用BenchmarkDotNet來跟蹤方法的性能。
要使用BenchmarkDotNet,你必須安裝BenchmarkDotNet軟件包。你可以通過Visual Studio 2022里面的NuGet軟件包管理器,或者在NuGet軟件包管理器控制臺執行以下命令來完成。
Install-Package BenchmarkDotNet
C#中的System.IO.Compression命名空間
System.IO.Compression命名空間包括壓縮文件和字符串的方法。它包含兩種壓縮算法。GZip 和 Brotli。在接下來的章節中,我們將研究如何在C#中使用GZip和Brotli壓縮算法對字符串數據進行壓縮和解壓。
我們將在下面的例子中使用以下文本。
string originalString = "To work with BenchmarkDotNet you must install the BenchmarkDotNet package. " +
"You can do this either via the NuGet Package Manager inside the Visual Studio 2019 IDE, " +
"or by executing the Install-Package BenchmarkDotNet command at the NuGet Package Manager Console";
在C#中使用GZip對數據進行壓縮和解壓
下面的代碼片斷顯示了如何在C#中使用GZipStream類來壓縮數據。注意,壓縮方法的參數是一個字節數組:
public static byte[] Compress(byte[] bytes)
{
using (var memoryStream = new MemoryStream())
{
using (var gzipStream = new GZipStream(memoryStream, CompressionLevel.Optimal))
{
gzipStream.Write(bytes, 0, bytes.Length);
}
return memoryStream.ToArray();
}
}
要解壓使用GZip算法壓縮過的數據,我們可以使用以下方法:
public static byte[] Decompress(byte[] bytes)
{
using (var memoryStream = new MemoryStream(bytes))
{
using (var outputStream = new MemoryStream())
{
using (var decompressStream = new GZipStream(memoryStream, CompressionMode.Decompress))
{
decompressStream.CopyTo(outputStream);
}
return outputStream.ToArray();
}
}
}
運行GZip壓縮算法
你可以使用下面的代碼片斷來執行我們剛剛創建的GZip壓縮方法:
byte[] dataToCompress = Encoding.UTF8.GetBytes(originalString);
byte[] compressedData = GZipCompressor.Compress(dataToCompress);
string compressedString = Encoding.UTF8.GetString(compressedData);
Console.WriteLine("Length of compressed string: " + compressedString.Length);
byte[] decompressedData = GZipCompressor.Decompress(compressedData);
string deCompressedString = Encoding.UTF8.GetString(decompressedData);
Console.WriteLine("Length of decompressed string: " + deCompressedString.Length);
當你運行上述代碼時,你會在控制臺窗口看到以下輸出:
圖1.GZip將原來259個字符的字符串壓縮成167個字符。
請注意,GZip從原始的259個字符的字符串中修剪了92個字符。因為原始字符串和解壓后的字符串應該是相同的,它們的長度也應該是相同的。
在C#中使用Brotli對數據進行壓縮和解壓
下面的代碼片斷說明了如何在C#中使用BrotliStream類來壓縮數據。與上面的GZip例子一樣,注意壓縮方法的參數是一個字節數組:
public static byte[] Compress(byte[] bytes)
{
using (var memoryStream = new MemoryStream())
{
using (var brotliStream = new BrotliStream(memoryStream, CompressionLevel.Optimal))
{
brotliStream.Write(bytes, 0, bytes.Length);
}
return memoryStream.ToArray();
}
}
而這里是你如何使用BrotliStream來解壓數據的:
public static byte[] Decompress(byte[] bytes)
{
using (var memoryStream = new MemoryStream(bytes))
{
using (var outputStream = new MemoryStream())
{
using (var decompressStream = new BrotliStream(memoryStream, CompressionMode.Decompress))
{
decompressStream.CopyTo(outputStream);
}
return outputStream.ToArray();
}
}
}
運行Brotli壓縮算法
下面的代碼片斷顯示了你如何使用我們上面創建的Brotli壓縮方法來壓縮一個字符串:
Console.WriteLine("Length of original string: " + originalString.Length);
byte[] dataToCompress = Encoding.UTF8.GetBytes(originalString);
byte[] compressedData = BrotliCompressor.Compress(dataToCompress);
string compressedString = Convert.ToBase64String(compressedData);
Console.WriteLine("Length of compressed string: " + compressedString.Length);
byte[] decompressedData = BrotliCompressor.Decompress(compressedData);
string deCompressedString = Convert.ToBase64String(decompressedData);
Console.WriteLine("Length of decompressed string: " + deCompressedString.Length);
當你運行該程序時,你將在控制臺窗口看到以下輸出:
圖2.Brotli將原來259個字符的字符串壓縮成121個字符。
正如你所看到的,Brotli的壓縮效果比GZip好得多。然而,壓縮率并不是故事的全部,我們將在下面看到。
用GZip和Brotli進行異步壓縮和解壓
請注意,我們之前使用的壓縮和解壓方法也有異步的對應方法。這里是使用GZip算法的壓縮和解壓方法的異步版本:
public async static Task<byte[]> CompressAsync(byte[] bytes)
{
using (var memoryStream = new MemoryStream())
{
using (var gzipStream = new GZipStream(memoryStream, CompressionLevel.Optimal))
{
await gzipStream.WriteAsync(bytes, 0, bytes.Length);
}
return memoryStream.ToArray();
}
}
public async static Task<byte[]> DecompressAsync(byte[] bytes)
{
using (var memoryStream = new MemoryStream(bytes))
{
using (var outputStream = new MemoryStream())
{
using (var decompressStream = new GZipStream(memoryStream, CompressionMode.Decompress))
{
await decompressStream.CopyToAsync(outputStream);
}
return outputStream.ToArray();
}
}
}
這里是使用Brotli的壓縮和解壓方法的異步版本:
public static async Task<byte[]> CompressAsync(byte[] bytes)
{
using (var memoryStream = new MemoryStream())
{
using (var brotliStream = new BrotliStream(memoryStream, CompressionLevel.Optimal))
{
await brotliStream.WriteAsync(bytes, 0, bytes.Length);
}
return memoryStream.ToArray();
}
}
public static async Task<byte[]> DecompressAsync(byte[] bytes)
{
using (var memoryStream = new MemoryStream(bytes))
{
using (var outputStream = new MemoryStream())
{
using (var brotliStream = new BrotliStream(memoryStream, CompressionMode.Decompress))
{
await brotliStream.CopyToAsync(outputStream);
}
return outputStream.ToArray();
}
}
}
在C#中用GZip和Brotli進行壓縮和解壓的基準測試
在我們之前創建的控制臺應用程序項目中,創建一個名為BenchmarkCompression.cs的新文件并輸入以下代碼:
[MemoryDiagnoser]
[Orderer(BenchmarkDotNet.Order.SummaryOrderPolicy.FastestToSlowest)]
[RankColumn]
public class BenchmarkCompression
{
string originalString = "To work with BenchmarkDotNet you must install the BenchmarkDotNet package. " +
"You can do this either via the NuGet Package Manager inside the Visual Studio 2019 IDE, " +
"or by executing the Install-Package BenchmarkDotNet command at the NuGet Package Manager Console";
[Benchmark]
public void GZipCompress()
{
byte[] dataToCompress = Encoding.UTF8.GetBytes(originalString);
var compressedData = GZipCompressor.Compress(dataToCompress);
}
[Benchmark]
public void BrotliCompress()
{
byte[] dataToCompress = Encoding.UTF8.GetBytes(originalString);
var compressedData = BrotliCompressor.Compress(dataToCompress);
}
}
當你運行基準時,你應該看到類似于下面圖3所示的控制臺輸出。
圖3.來自BenchmarkDotNet的結果...GZip贏了!
顯然,在選擇壓縮算法時,壓縮率并不是唯一的考慮因素。盡管與GZip相比,你可以使用Brotli實現更好的壓縮,但額外的壓縮是以性能為代價的。GZip在壓縮和解壓數據方面明顯比Brotli快。
當對你的.NET應用程序進行基準測試時,你應該始終確保你的項目在發布模式下運行。原因是編譯器為調試和發布模式優化代碼的方式不同。關于基準測試和應用程序的性能,我在以后的文章中會有更多論述。
原文鏈接:https://juejin.cn/post/7127103519835815973
相關推薦
- 2023-01-28 詳解如何利用C#實現漢字轉拼音功能_C#教程
- 2022-03-30 android?RecyclerView添加footerview詳解_Android
- 2022-07-30 Redis如何使用HyperLogLog的實現_Redis
- 2022-09-26 Josephus_problem_bidirectional 雙向約瑟夫問題
- 2022-07-09 如何給 SAP Commerce Cloud Site 設置默認語言
- 2023-02-09 go?sync?Waitgroup數據結構實現基本操作詳解_Golang
- 2022-09-27 Android內置的OkHttp用法介紹_Android
- 2022-05-22 Nginx反向代理與負載均衡概念理解及模塊使用_nginx
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支