C#中對字符串進行壓縮和解壓的實現(xiàn)
利用GZip和Brotli壓縮方法的優(yōu)勢,減少字符串數(shù)據(jù)的大小,提高.NET核心應用程序的性能。
在開發(fā)應用程序時,你經(jīng)常需要處理字符串。由于字符串對象在性能方面的成本很高,你經(jīng)常想壓縮你的字符串內(nèi)容,即字符串對象中的數(shù)據(jù),以減少有效載荷。有幾個庫可以做到這一點,但兩個流行的技術是GZip和Brotli。
在這篇文章中,我們將討論如何在C#中使用GZip和Brotli算法對字符串進行壓縮和解壓。要使用這里提供的代碼示例,你的系統(tǒng)中應該安裝有Visual Studio 2022。如果你還沒有副本,你可以在這里下載Visual Studio 2022。
在Visual Studio 2022中創(chuàng)建一個控制臺應用程序項目
首先,讓我們在Visual Studio中創(chuàng)建一個.NET Core控制臺應用程序項目。假設你的系統(tǒng)中已經(jīng)安裝了Visual Studio 2022,按照下面的步驟創(chuàng)建一個新的.NET Core控制臺應用程序項目:
- 啟動Visual Studio IDE。
- 點擊 "創(chuàng)建一個新項目"。
- 在 "創(chuàng)建一個新項目 "窗口中,從顯示的模板列表中選擇 "控制臺應用程序"。
- 點擊 "下一步"。
- 在接下來顯示的 "配置你的新項目 "窗口中,指定新項目的名稱和位置。
- 在 "其他信息 "窗口中,選擇.NET 6.0作為運行時間,然后點擊下一步。
- 點擊 "創(chuàng)建"。
我們將使用這個項目來說明下面的字符串壓縮和解壓縮。但首先我們要安裝一個基準測試包BenchmarkDotNet,它將使我們能夠衡量我們從壓縮中獲得的好處。
安裝BenchmarkDotNet NuGet包
基準測試代碼對于了解你的應用程序的性能至關重要。在這篇文章中,我們將利用BenchmarkDotNet來跟蹤方法的性能。
要使用BenchmarkDotNet,你必須安裝BenchmarkDotNet軟件包。你可以通過Visual Studio 2022里面的NuGet軟件包管理器,或者在NuGet軟件包管理器控制臺執(zhí)行以下命令來完成。
Install-Package BenchmarkDotNet
C#中的System.IO.Compression命名空間
System.IO.Compression命名空間包括壓縮文件和字符串的方法。它包含兩種壓縮算法。GZip 和 Brotli。在接下來的章節(jié)中,我們將研究如何在C#中使用GZip和Brotli壓縮算法對字符串數(shù)據(jù)進行壓縮和解壓。
我們將在下面的例子中使用以下文本。
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對數(shù)據(jù)進行壓縮和解壓
下面的代碼片斷顯示了如何在C#中使用GZipStream類來壓縮數(shù)據(jù)。注意,壓縮方法的參數(shù)是一個字節(jié)數(shù)組:
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算法壓縮過的數(shù)據(jù),我們可以使用以下方法:
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壓縮算法
你可以使用下面的代碼片斷來執(zhí)行我們剛剛創(chuàng)建的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對數(shù)據(jù)進行壓縮和解壓
下面的代碼片斷說明了如何在C#中使用BrotliStream類來壓縮數(shù)據(jù)。與上面的GZip例子一樣,注意壓縮方法的參數(shù)是一個字節(jié)數(shù)組:
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來解壓數(shù)據(jù)的:
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壓縮算法
下面的代碼片斷顯示了你如何使用我們上面創(chuàng)建的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進行壓縮和解壓的基準測試
在我們之前創(chuàng)建的控制臺應用程序項目中,創(chuàng)建一個名為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實現(xiàn)更好的壓縮,但額外的壓縮是以性能為代價的。GZip在壓縮和解壓數(shù)據(jù)方面明顯比Brotli快。
當對你的.NET應用程序進行基準測試時,你應該始終確保你的項目在發(fā)布模式下運行。原因是編譯器為調(diào)試和發(fā)布模式優(yōu)化代碼的方式不同。關于基準測試和應用程序的性能,我在以后的文章中會有更多論述。
到此這篇關于C#中對字符串進行壓縮和解壓的實現(xiàn)的文章就介紹到這了,更多相關C# 字符串壓縮和解壓內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
C# JSON格式化轉(zhuǎn)換輔助類 ConvertJson
本文介紹使用C#原生代碼實現(xiàn) JSON格式化以及各種類型轉(zhuǎn)化JSON的輔助類,幫助開發(fā)人員快速開發(fā)。2016-04-04C#實現(xiàn)簡易灰度圖和酷炫HeatMap熱力圖winform(附DEMO)
本文主要介紹了C#實現(xiàn)簡易灰度圖和酷炫HeatMap熱力圖winform(附DEMO),文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-12-12