Skip to content

Instantly share code, notes, and snippets.

@xeoncross
Last active November 2, 2019 17:58
Show Gist options
  • Select an option

  • Save xeoncross/ec34fc9a1c7acb7642c94a85b3cdc0dd to your computer and use it in GitHub Desktop.

Select an option

Save xeoncross/ec34fc9a1c7acb7642c94a85b3cdc0dd to your computer and use it in GitHub Desktop.
Writing a large number of ints to a byte slice is slower when using https://golang.org/pkg/encoding/binary/#Write
package bytewriter
import (
"bytes"
"encoding/binary"
"testing"
)
func BenchmarkBinary(b *testing.B) {
var values []uint16
var i uint16
for i = 0; i < 1000; i++ {
values = append(values, i)
}
b.ResetTimer()
buf := new(bytes.Buffer)
for i := 0; i < b.N; i++ {
for _, value := range values {
err := binary.Write(buf, binary.LittleEndian, uint16(value))
if err != nil {
b.Error(err)
}
}
}
// fmt.Printf("Length: %d\n", buf.Len())
buf.Len()
}
func BenchmarkRaw(b *testing.B) {
var values []uint16
var i uint16
for i = 0; i < 1000; i++ {
values = append(values, i)
}
b.ResetTimer()
var buf []byte
v := make([]byte, 2)
for i := 0; i < b.N; i++ {
for _, value := range values {
binary.BigEndian.PutUint16(v, uint16(value))
buf = append(buf, v...)
}
}
// fmt.Printf("Length: %d\n", buf.Len())
_ = len(buf)
}
goos: darwin
goarch: amd64
pkg: bytewriter
BenchmarkBinary-8 26964 42204 ns/op
BenchmarkRaw-8 463342 5106 ns/op
@xeoncross
Copy link
Copy Markdown
Author

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