下面是我的测试代码:
package app
import (
"bytes"
"testing"
)
const ALLOC_SIZE = 64 * 1024
func BenchmarkFunc1(b *testing.B) {
for i := 0; i < b.N; i++ {
v := make([]byte, ALLOC_SIZE)
fill(v, '1', 0, ALLOC_SIZE)
}
}
func BenchmarkFunc2(b *testing.B) {
for i := 0; i < b.N; i++ {
b := new(bytes.Buffer)
b.Grow(ALLOC_SIZE)
fill(b.Bytes(), '2', 0, ALLOC_SIZE)
}
}
func fill(slice []byte, val byte, start, end int) {
for i := start; i < end; i++ {
slice = append(slice, val)
}
}结果:
at 19:05:47 ❯ go test -bench . -benchmem -gcflags=-m
# app [app.test]
./main_test.go:25:6: can inline fill
./main_test.go:10:6: can inline BenchmarkFunc1
./main_test.go:13:7: inlining call to fill
./main_test.go:20:9: inlining call to bytes.(*Buffer).Grow
./main_test.go:21:15: inlining call to bytes.(*Buffer).Bytes
./main_test.go:21:7: inlining call to fill
./main_test.go:10:21: b does not escape
./main_test.go:12:12: make([]byte, ALLOC_SIZE) escapes to heap
./main_test.go:20:9: BenchmarkFunc2 ignoring self-assignment in bytes.b.buf = bytes.b.buf[:bytes.m·3]
./main_test.go:17:21: b does not escape
./main_test.go:19:11: new(bytes.Buffer) does not escape
./main_test.go:25:11: slice does not escape
# app.test
/var/folders/45/vh6dxx396d590hxtz7_9_smmhqf0sq/T/go-build1328509211/b001/_testmain.go:35:6: can inline init.0
/var/folders/45/vh6dxx396d590hxtz7_9_smmhqf0sq/T/go-build1328509211/b001/_testmain.go:43:24: inlining call to testing.MainStart
/var/folders/45/vh6dxx396d590hxtz7_9_smmhqf0sq/T/go-build1328509211/b001/_testmain.go:43:42: testdeps.TestDeps{} escapes to heap
/var/folders/45/vh6dxx396d590hxtz7_9_smmhqf0sq/T/go-build1328509211/b001/_testmain.go:43:24: &testing.M{...} escapes to heap
goos: darwin
goarch: amd64
pkg: app
cpu: Intel(R) Core(TM) i7-7700HQ CPU @ 2.80GHz
BenchmarkFunc1-8 8565 118348 ns/op 393217 B/op 4 allocs/op
BenchmarkFunc2-8 23332 53043 ns/op 65536 B/op 1 allocs/op
PASS
ok app 2.902s我的假设是,使用由make创建的固定大小的片比使用bytes.Buffer便宜得多,因为编译器可能能够知道在编译时需要分配的内存大小。使用bytes.Buffer看起来有点像运行时的东西。然而,结果并不是我所期望的。
对此有什么解释吗?
发布于 2021-07-19 18:30:01
您混淆了切片的容量和长度。
v := make([]byte, ALLOC_SIZE)V现在是一个长度为64k、容量为64k的切片。将任何内容附加到此切片后,Go会强制将后备数组复制到一个新的、更大的数组中。
b := new(bytes.Buffer)
b.Grow(ALLOC_SIZE)
v := b.Bytes()这里,v是长度为0且容量为64k的切片。您可以在不进行任何重新分配的情况下将64k字节附加到此片中,因为它最初是空的,但64k后备数组已准备就绪。
总而言之,您正在将已填充到容量的切片与具有相同容量的空切片进行比较。
要进行公平的比较,请将您的第一个基准测试更改为也分配一个空片:
func BenchmarkFunc1(b *testing.B) {
for i := 0; i < b.N; i++ {
v := make([]byte, 0, ALLOC_SIZE) // note the three argument form
fill(v, '1', 0, ALLOC_SIZE)
}
}goos: linux
goarch: amd64
pkg: foo
cpu: Intel(R) Core(TM) i5-10210U CPU @ 1.60GHz
BenchmarkFunc1-8 23540 51990 ns/op 65536 B/op 1 allocs/op
BenchmarkFunc2-8 24939 45096 ns/op 65536 B/op 1 allocs/op在https://blog.golang.org/slices-intro中详细介绍了片、数组、长度和容量之间的关系
https://stackoverflow.com/questions/68438818
复制相似问题