Skip to content

Instantly share code, notes, and snippets.

@lucas-clemente
Created September 6, 2016 11:47
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 lucas-clemente/9e9289da91eaf144a76f3dca04c8baf1 to your computer and use it in GitHub Desktop.
Save lucas-clemente/9e9289da91eaf144a76f3dca04c8baf1 to your computer and use it in GitHub Desktop.
package bench
import (
"bytes"
"encoding/binary"
"io"
"testing"
)
func BenchmarkWriteByte(b *testing.B) {
var buf bytes.Buffer
for i := 0; i < b.N; i++ {
buf.Reset()
buf.WriteByte(uint8(i))
buf.WriteByte(uint8(i >> 8))
buf.WriteByte(uint8(i >> 16))
buf.WriteByte(uint8(i >> 24))
}
}
func BenchmarkWrite(b *testing.B) {
var buf bytes.Buffer
for i := 0; i < b.N; i++ {
buf.Reset()
buf.Write([]byte{uint8(i), uint8(i >> 8), uint8(i >> 16), uint8(i >> 24)})
}
}
func BenchmarkReadByte(b *testing.B) {
r := bytes.NewReader([]byte{0xde, 0xad, 0xbe, 0xef})
for i := 0; i < b.N; i++ {
r.Seek(0, io.SeekStart)
var b1, b2, b3, b4 uint8
var err error
if b1, err = r.ReadByte(); err != nil {
panic(err)
}
if b2, err = r.ReadByte(); err != nil {
panic(err)
}
if b3, err = r.ReadByte(); err != nil {
panic(err)
}
if b4, err = r.ReadByte(); err != nil {
panic(err)
}
n := uint32(b1) + uint32(b2)<<8 + uint32(b3)<<16 + uint32(b4)<<24
_ = n
}
}
func BenchmarkRead(b *testing.B) {
r := bytes.NewReader([]byte{0xde, 0xad, 0xbe, 0xef})
for i := 0; i < b.N; i++ {
r.Seek(0, io.SeekStart)
s := make([]byte, 4)
if _, err := r.Read(s); err != nil {
panic(err)
}
n := binary.LittleEndian.Uint32(s)
_ = n
}
}
func BenchmarkReadSlice(b *testing.B) {
s := []byte{0xde, 0xad, 0xbe, 0xef}
for i := 0; i < b.N; i++ {
n := binary.LittleEndian.Uint32(s[0:])
_ = n
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment