snappier

How to use Snappy compression in C# with Snappier

  • 2 min

Snappier is an open-source library that implements the Snappy compression algorithm in C#, for use in .NET applications.

Snappy is a compression algorithm developed in C++ by Google, known for its speed, efficiency, and low CPU and memory consumption.

Unlike other compression algorithms, such as Gzip, Snappy is oriented towards applications where speed is critical, such as caching systems and real-time processing.

Among the many alternatives available for using Snappy in .NET, I like the Snappier library. Unlike, for example, https://github.com/robertvazan/snappy.net, which is a wrapper around the C++ library, Snappier is a complete port to C#.

Being a full managed port ensures we won’t have memory leaks or “weird errors” that can happen when using Wrappers. Furthermore, we can use it cross-platform, not just on Windows.

On the other hand, it is highly optimized. The speed we get with Snappier is similar to what we would get using the C++ library directly. This is especially important, considering that Snappy’s goal is speed.

Snappier is compatible with .NET Framework 4.6.1 or later, and .NET Core 2.0 or later. However, only when using NET 3.0 or later do we get performance similar to that achieved in C++.

How to Use Snappier

We can easily add the library to a .NET project via the corresponding NuGet package.

Install-Package Snappier

Here is a simple example of how to use Snappier, taken from the library’s documentation.

byte[] data = {0, 1, 2}; 

// Compression example
byte[] compressed = Snappy.CompressToArray(data);

// Decompression example
byte[] decompressed = Snappy.DecompressToArray(compressed);
Copied!

Although normally we would use Streams to optimize performance. Here is an example of how to use Snappier with Streams.

using var fileStream = File.OpenRead("somefile.txt");

// Compression example
using var compressed = new MemoryStream();
using (var compressor = new SnappyStream(compressed, CompressionMode.Compress, false)) {
    await fileStream.CopyToAsync(compressor);
}

// Decompression example
compressed.Position = 0;
using var decompressor = new SnappyStream(compressed, CompressionMode.Decompress);
var buffer = new byte[65536];
var bytesRead = decompressor.Read(buffer, 0, buffer.Length);
while (bytesRead > 0)
{
    bytesRead = decompressor.Read(buffer, 0, buffer.Length)
}
Copied!

As we can see, it only takes a few lines of code to compress and decompress data with the Snappy algorithm, quickly and efficiently.