Last active
November 2, 2019 17:58
-
-
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
This file contains hidden or 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 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) | |
| } |
This file contains hidden or 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
| goos: darwin | |
| goarch: amd64 | |
| pkg: bytewriter | |
| BenchmarkBinary-8 26964 42204 ns/op | |
| BenchmarkRaw-8 463342 5106 ns/op |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://github.com/Xeoncross/go-experiment