Last active
July 20, 2021 05:22
-
-
Save IzumiSy/881634208ff90bba05f9937635dfb2d8 to your computer and use it in GitHub Desktop.
bytes.Buffer vs make
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 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) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Result