Skip to content

Instantly share code, notes, and snippets.

@carterpeel
Created January 30, 2022 16:38
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 carterpeel/d9d06a9a44193d1d648499c2b112a1f1 to your computer and use it in GitHub Desktop.
Save carterpeel/d9d06a9a44193d1d648499c2b112a1f1 to your computer and use it in GitHub Desktop.
Binary type switch is slow
package fastbinary
import (
"bytes"
"encoding/binary"
"io"
"testing"
)
func BenchmarkInternalBinary_Read(b *testing.B) {
inbuf := []byte(" \n \nAccording to all known laws\nof aviation,\n\n \nthere is no way a bee\nshould be able to fly.\n\n \nIts wings are too small to get\nits fat little body off the ground.\n\n \nThe bee, of course, flies anyway\n\n \nbecause bees don't care\nwhat humans think is impossible.\n\n \nYellow, black. Yellow, black.\nYellow, black. Yellow, black.\n\n \nOoh, black and yellow!\nLet's shake it up a little.\n\n \nBarry! Breakfast is ready!\n\n \nOoming!\n\n \nHang on a second.")
outbuf := int16(0)
for i := 0; i < b.N; i++ {
for rds := 0; rds < 10000; rds++ {
if err := binary.Read(bytes.NewReader(inbuf), binary.LittleEndian, &outbuf); err != nil {
b.Fatalf("Error reading into buffer: %v\n", err)
}
}
}
}
func BenchmarkFastBinary_Read(b *testing.B) {
inbuf := []byte(" \n \nAccording to all known laws\nof aviation,\n\n \nthere is no way a bee\nshould be able to fly.\n\n \nIts wings are too small to get\nits fat little body off the ground.\n\n \nThe bee, of course, flies anyway\n\n \nbecause bees don't care\nwhat humans think is impossible.\n\n \nYellow, black. Yellow, black.\nYellow, black. Yellow, black.\n\n \nOoh, black and yellow!\nLet's shake it up a little.\n\n \nBarry! Breakfast is ready!\n\n \nOoming!\n\n \nHang on a second.")
outbuf := int16(0)
for i := 0; i < b.N; i++ {
for rds := 0; rds < 10000; rds++ {
if err := BinaryReadNoTypeSwitch(bytes.NewReader(inbuf), &outbuf); err != nil {
b.Fatalf("Error reading into buffer: %v\n", err)
}
}
}
}
func BinaryReadNoTypeSwitch(r io.Reader, data *int16) error {
bs := make([]byte, Int16DataSize)
if _, err := io.ReadFull(r, bs); err != nil {
return err
}
*data = int16(binary.LittleEndian.Uint16(bs))
return nil
}
@carterpeel
Copy link
Author

Benchmark results:

goos: darwin
goarch: amd64
pkg: ledfx/integrations/airplay2/codec/fastbinary
cpu: Intel(R) Core(TM) i9-9880H CPU @ 2.30GHz
BenchmarkInternalBinary_Read
BenchmarkInternalBinary_Read-16    	    1615	    643031 ns/op
BenchmarkFastBinary_Read
BenchmarkFastBinary_Read-16        	    2172	    548797 ns/op
PASS

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment