Skip to content

Instantly share code, notes, and snippets.

@IzumiSy
Last active July 20, 2021 05:22
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 IzumiSy/881634208ff90bba05f9937635dfb2d8 to your computer and use it in GitHub Desktop.
Save IzumiSy/881634208ff90bba05f9937635dfb2d8 to your computer and use it in GitHub Desktop.
bytes.Buffer vs make
package app
import (
"bytes"
"testing"
)
const ALLOC_SIZE = 64 * 1024 * 1024
func BenchmarkAlloc1(b *testing.B) {
for i := 0; i < b.N; i++ {
v := make([]byte, 0, ALLOC_SIZE)
if len(v) != 0 {
b.Fatal("oops")
}
}
}
func BenchmarkAlloc2(b *testing.B) {
for i := 0; i < b.N; i++ {
v := new(bytes.Buffer)
if len(v.Bytes()) != 0 {
b.Fatal("oops")
}
}
}
func BenchmarkAlloc3(b *testing.B) {
for i := 0; i < b.N; i++ {
v := new(bytes.Buffer)
v.Grow(ALLOC_SIZE)
if len(v.Bytes()) != 0 {
b.Fatal("oops")
}
}
}
func BenchmarkWrite1(b *testing.B) {
for i := 0; i < b.N; i++ {
v := make([]byte, 0, ALLOC_SIZE)
fill(v, '1', 0, ALLOC_SIZE)
}
}
func BenchmarkWrite2(b *testing.B) {
for i := 0; i < b.N; i++ {
v := new(bytes.Buffer)
fill(v.Bytes(), '2', 0, ALLOC_SIZE)
}
}
func BenchmarkWrite3(b *testing.B) {
for i := 0; i < b.N; i++ {
v := new(bytes.Buffer)
v.Grow(ALLOC_SIZE)
fill(v.Bytes(), '3', 0, ALLOC_SIZE)
}
}
func fill(slice []byte, val byte, start, end int) {
for i := start; i < end; i++ {
slice = append(slice, val)
}
}
@IzumiSy
Copy link
Author

IzumiSy commented Jul 20, 2021

Result

at 13:56:36 ❯ go test -bench . -benchmem
goos: darwin
goarch: amd64
pkg: app
cpu: Intel(R) Core(TM) i7-7700HQ CPU @ 2.80GHz
BenchmarkAlloc1-8            337           2976935 ns/op        67108871 B/op          1 allocs/op
BenchmarkAlloc2-8       1000000000               0.3202 ns/op          0 B/op          0 allocs/op
BenchmarkAlloc3-8            375           2950193 ns/op        67108873 B/op          1 allocs/op
BenchmarkWrite1-8             16          66047937 ns/op        67108876 B/op          1 allocs/op
BenchmarkWrite2-8             12          85604838 ns/op        338720834 B/op        54 allocs/op
BenchmarkWrite3-8             26          44761869 ns/op        67108871 B/op          1 allocs/op
PASS
ok      app     6.945s

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