Skip to content

Instantly share code, notes, and snippets.

@erikdubbelboer
Created May 10, 2020 08:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erikdubbelboer/3e7b044e300be6a7ff2b76e6922052ec to your computer and use it in GitHub Desktop.
Save erikdubbelboer/3e7b044e300be6a7ff2b76e6922052ec to your computer and use it in GitHub Desktop.
// +build ignore
package main
import (
"bytes"
"compress/gzip"
"fmt"
"io/ioutil"
"net/http"
"testing"
"time"
"github.com/andybalholm/brotli"
)
func main() {
var data [][]byte
urls := []string{
"https://en.wikipedia.org/wiki/Wiki",
"https://www.google.com/",
"https://www.redditstatic.com/reddit.6-fmKdWEVQE.css",
"https://www.redditstatic.com/videoplayer.7Cfu_8q9HGE.js",
"https://github.githubassets.com/images/search-key-slash.svg",
"https://github.githubassets.com/assets/frameworks-c9da5f32.js",
"https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.11/vue.min.js",
}
max := 0
for _, u := range urls {
res, err := http.Get(u)
if err != nil {
panic(err)
}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
panic(err)
}
res.Body.Close()
data = append(data, body)
if len(body) > max {
max = len(body)
}
}
buf := bytes.Buffer{}
buf.Grow(max)
b := brotli.NewWriterLevel(&buf, 1)
n := 0
a := 0.0
start := time.Now()
for _, d := range data {
a += testing.AllocsPerRun(100, func() {
if _, err := b.Write(d); err != nil {
panic(err)
}
if err := b.Flush(); err != nil {
panic(err)
}
n += buf.Len()
buf.Reset()
//b = brotli.NewWriterLevel(&buf, 4)
b.Reset(&buf)
})
}
a /= float64(len(data))
fmt.Println("allocs per run brotli:", a, time.Since(start))
g, _ := gzip.NewWriterLevel(&buf, 1)
m := 0
a = 0.0
start = time.Now()
for _, d := range data {
a += testing.AllocsPerRun(100, func() {
if _, err := g.Write(d); err != nil {
panic(err)
}
if err := g.Flush(); err != nil {
panic(err)
}
m += buf.Len()
buf.Reset()
//g, _ = gzip.NewWriterLevel(&buf, 6)
g.Reset(&buf)
})
}
a /= float64(len(data))
fmt.Println("allocs per run gzip:", a, time.Since(start))
n /= (len(data) * 100)
m /= (len(data) * 100)
fmt.Println("brotli:", n, "gzip:", m, "brotli is:", 100-float64(n)/float64(m)*100, "% smaller")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment