最近一直在優化項目的性能,就在前幾天找到了一些資料,終於有方案了,那就是壓縮數據。
一丶前端和后端的壓縮和解壓縮流程
二丶優點和缺點
優點:①字符串的壓縮率能夠達到70%-80%左右
②字符串數量更少了
缺點:①CPU的開銷會大一點,不過在可承受范圍之內
三丶通過標記來說明數據是否壓縮過
這個一開始是沒有想到,是經理提醒我的,通過在數據(字符串)的最前端添加一個標記來說明數據是否壓縮過。
因為只有當數據大於一定數量的時候才進行壓縮操作。
四丶測試(簡單的測試)
環境:1.啟動500線程 (相當於500個客戶端)
2.500個線程同時調用
3.服務端和客戶端在同一個局域網的兩台PC機
4.未壓縮的字符串長度為65000,壓縮之后長度為8400
測試結果:
結果:其實測試的結果很明顯了,通過壓縮數據來減少網絡數據量的傳輸,確實可以提高速度。
五丶代碼
1 public class CompressionHelper 2 { 3 public static string Compress(string value) 4 { 5 string result = string.Empty; 6 try 7 { 8 byte[] buffer = Encoding.UTF8.GetBytes(value); 9 using (MemoryStream memoryStream = new MemoryStream()) 10 { 11 using (DeflateStream deflateStream = new DeflateStream(memoryStream, CompressionMode.Compress, true)) 12 { 13 deflateStream.Write(buffer, 0, buffer.Length); 14 } 15 result = Convert.ToBase64String(memoryStream.ToArray()); 16 } 17 } 18 catch (InvalidDataException invalidData) 19 { 20 //Log21 } 22 catch (Exception exception) 23 { 24 //Log25 } 26 return result; 27 } 28 29 public static string Decompress(string value) 30 { 31 string result = string.Empty; 32 try 33 { 34 byte[] bytes = Convert.FromBase64String(value); 35 using (MemoryStream outStream = new MemoryStream()) 36 { 37 using (MemoryStream inStream = new MemoryStream(bytes)) 38 { 39 using (DeflateStream deflateStream = new DeflateStream(inStream, CompressionMode.Decompress, true)) 40 { 41 int readLength = 0; 42 byte[] buffer = new byte[1024]; 43 while ((readLength = deflateStream.Read(buffer, 0, buffer.Length)) > 0) 44 { 45 outStream.Write(buffer, 0, readLength); 46 } 47 } 48 } 49 result = Encoding.UTF8.GetString(outStream.ToArray()); 50 } 51 } 52 catch (InvalidDataException invalidData) 53 { 54 //Log55 } 56 catch (Exception exception) 57 { 58 //Log59 } 60 return result; 61 } 62 }
以同步至:個人文章目錄索引