Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

Xeoncross commented Nov 2, 2019

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.