Skip to content

Instantly share code, notes, and snippets.

@nakabonne
Created June 17, 2021 09:56
Show Gist options
  • Save nakabonne/1ee4ce790fdb02a869afa58e6e7d8517 to your computer and use it in GitHub Desktop.
Save nakabonne/1ee4ce790fdb02a869afa58e6e7d8517 to your computer and use it in GitHub Desktop.
package main
import (
"bytes"
"encoding/binary"
"testing"
)
type Data struct {
ID uint32
Timestamp uint32
Value int16
}
func EncodeWithByteOrder() {
data := &Data{
ID: 100, Timestamp: 1600000000, Value: 10,
}
buf := make([]byte, 10)
binary.BigEndian.PutUint32(buf[0:], data.ID)
binary.BigEndian.PutUint32(buf[4:], data.Timestamp)
binary.BigEndian.PutUint16(buf[8:], uint16(data.Value))
}
func EncodeWithByteStream() {
data := &Data{
ID: 100, Timestamp: 1600000000, Value: 10,
}
buf := &bytes.Buffer{}
_ = binary.Write(buf, binary.BigEndian, data)
}
func BenchmarkEncodeWithByteOrder(b *testing.B) {
for i := 1; i < b.N; i++ {
EncodeWithByteOrder()
}
}
func BenchmarkEncodeWithStream(b *testing.B) {
for i := 1; i < b.N; i++ {
EncodeWithByteStream()
}
}
@nakabonne
Copy link
Author

$ go test -benchmem -bench=. .
goos: darwin
goarch: amd64
pkg: hoge
cpu: Intel(R) Core(TM) i7-8559U CPU @ 2.70GHz
BenchmarkEncodeWithByteOrder-8          1000000000               1.118 ns/op           0 B/op          0 allocs/op
BenchmarkEncodeWithStream-8              5775616               202.5 ns/op           144 B/op          4 allocs/op
PASS
ok      hoge    2.877s

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