Created
June 17, 2021 09:56
-
-
Save nakabonne/1ee4ce790fdb02a869afa58e6e7d8517 to your computer and use it in GitHub Desktop.
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 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() | |
} | |
} |
Author
nakabonne
commented
Jun 17, 2021
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment