Created
January 30, 2022 16:38
-
-
Save carterpeel/d9d06a9a44193d1d648499c2b112a1f1 to your computer and use it in GitHub Desktop.
Binary type switch is slow
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Benchmark results: