Skip to content

Instantly share code, notes, and snippets.

@danmoseley
Created April 14, 2023 18:20
Show Gist options
  • Save danmoseley/68675bd70d78d1fd0733c168c7b498ed to your computer and use it in GitHub Desktop.
Save danmoseley/68675bd70d78d1fd0733c168c7b498ed to your computer and use it in GitHub Desktop.
brotli vs deflate
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
namespace compressionspeed
{
internal class Program
{
static TimeSpan last = TimeSpan.Zero;
static long lastSize = 0;
static void Main(string[] args)
{
Console.WriteLine("vs Zip with Optimal compression level (large dll)");
DoTest(CompressionLevel.Optimal, false);
DoTest(CompressionLevel.Optimal, false, baseline:true) ;
DoTest(CompressionLevel.NoCompression);
DoTest(CompressionLevel.Fastest);
DoTest(CompressionLevel.Optimal);
DoTest(CompressionLevel.SmallestSize);
Console.WriteLine();
DoTest2(CompressionLevel.Optimal, false);
DoTest2(CompressionLevel.NoCompression);
DoTest2(CompressionLevel.Fastest);
DoTest2(CompressionLevel.Optimal);
DoTest2(CompressionLevel.SmallestSize);
}
static void DoTest(CompressionLevel cl, bool print = true, bool baseline = false)
{
Directory.CreateDirectory(@"c:\tempzip");
var dest = Path.Combine(@"c:\tempzip", Path.GetRandomFileName() + Enum.Format(typeof(CompressionLevel), cl, "g"));
Stopwatch sw = Stopwatch.StartNew();
try
{
//ZipFile.(@"c:\tempzip\enwiki8", dest, cl, includeBaseDirectory: false);
using (ZipArchive zip = ZipFile.Open(dest, ZipArchiveMode.Create))
{
zip.CreateEntryFromFile(@"c:\tempzip\WindowsCodecsRaw.dll", "data/path/something.txt", cl);
}
}
finally
{
sw.Stop();
TimeSpan @this = sw.Elapsed;
long size = new FileInfo(dest).Length;
if (baseline)
{
last = @this; lastSize = size;
}
if (print)
{
Console.Write($"{cl,20}: ");
Console.Write($"ZIP {Math.Round((double)(size - lastSize) / lastSize * 100, 0)} % size");
Console.WriteLine($" {Math.Round((@this - last) / last * 100, 0)} % speed");
}
File.Delete(dest);
}
}
static void DoTest2(CompressionLevel cl, bool print = true)
{
Directory.CreateDirectory(@"c:\tempzip");
var dest = Path.Combine(@"c:\tempzip", Path.GetRandomFileName() + Enum.Format(typeof(CompressionLevel), cl, "g"));
Stopwatch sw = Stopwatch.StartNew();
try
{
using (FileStream input = File.OpenRead(@"c:\tempzip\WindowsCodecsRaw.dll"))
using (FileStream output = File.Create(dest))
using (BrotliStream compressor = new BrotliStream(output, cl))
{
input.CopyTo(compressor);
}
}
finally
{
sw.Stop();
TimeSpan @this = sw.Elapsed;
long size = new FileInfo(dest).Length;
if (print)
{
Console.Write($"{cl,20}: ");
Console.Write($"BROTLI {Math.Round((double)(size - lastSize) / lastSize * 100, 0), 4} % size");
Console.WriteLine($" {Math.Round((@this - last) / last * 100, 0), 4} % speed");
}
File.Delete(dest);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment