1
  1. 我不明白“为什么 gzip/deflate 压缩小文件会导致许多尾随零?”(为什么 gzip/deflate 压缩一个小文件会导致很多尾随零?

  2. 您将如何在 .NET 环境中将 ½-2 KB 的少量数据压缩到最小大小?(运行时对我来说不是问题。我可以用速度换大小吗?我应该使用第 3 方产品吗?开发者许可费用可以,但运行时许可不行。)

  3. 关于如何改进以下代码的任何建议:
    (a)更高的压缩比?
    (b) 更恰当地使用流?

这是需要改进的 C# 代码:

private static byte[] SerializeAndCompress(MyClass myObject)  
{
   using (var inStream = new System.IO.MemoryStream())
   {

     Serializer.Serialize< MyClass >(inStream, myObject); // PROTO-buffer  serialization. (Code not included here.)
     byte[] gZipBytearray = GZipCompress(inStream);
     return gZipBytearray;
   }
}

private static Byte[] GZipCompress(MemoryStream inStream)
{
   inStream.Position = 0;

   byte[] byteArray;
   {
      using (MemoryStream outStream = new MemoryStream())
      {
         bool LeaveOutStreamOpen = true;
         using (GZipStream compressStream = new GZipStream(outStream, 
            CompressionMode.Compress, LeaveOutStreamOpen))
         {
         // Copy the input stream into the compression stream.
         // inStream.CopyTo(Compress); TODO: "Uncomment" this line and remove the next one after upgrade to .NET 4 or later.
            CopyFromStreamToStream(inStream, compressStream);
     }
     byteArray = CreateByteArrayFromStream(outStream); // outStream is complete first after compressStream have been closed.
      }
   }
   return byteArray;
}

private static void CopyFromStreamToStream(Stream sourceStream, Stream destinationStream)
{
   byte[] buffer = new byte[4096];
   int numRead;
   while ((numRead = sourceStream.Read(buffer, 0, buffer.Length)) != 0)
   {
     destinationStream.Write(buffer, 0, numRead);
   }
}

private static byte[] CreateByteArrayFromStream(MemoryStream outStream)
{
   byte[] byteArray = new byte[outStream.Length];
   outStream.Position = 0;
   outStream.Read(byteArray, 0, (int)outStream.Length);
   return byteArray;
}
4

0 回答 0