写到第十一个的时候,就发生了内存分配。为什么会这样?
```go
func numAllocs(fn func()) uint64 {
defer runtime.GOMAXPROCS(runtime.GOMAXPROCS(1))
var m1, m2 runtime.MemStats
runtime.ReadMemStats(&m1)
fn()
runtime.ReadMemStats(&m2)
return m2.Mallocs - m1.Mallocs
}
func TestStrings_numAllocs(t *testing.T) {
// Builder’s inner slice’s capacity: 10
// Builder’s inner slice’s length: 5
// current_capacity * 2 + n
var sql strings.Builder
sql.Grow(10) // capacity should 30
allocs := numAllocs(func() {
for i := 0; i < 11; {
sql.WriteByte('a')
i++
}
_ = sql.String()
})
if allocs > 0 {
t.Fatalf("got %d alloc(s); want 0", allocs)
}
}
```
有疑问加站长微信联系(非本文作者)