先把简单的代码贴出来,然后再废话。
先是benchmark的命令
go test -bench=Poin -memprofile=pointermem.pprof -memprofilerate=1 -benchmem
go test -bench=Value -memprofile=valuemem.pprof -memprofilerate=1 -benchmem
然后是pprof的结果,先是pointer的,再是value的,可以看到pointer的报告2allocs/op
package main
type mytype struct {
field1 string
field2 string
field3 string
field4 string
field5 string
field6 string
field7 string
field8 string
field9 string
}
func returnValue() mytype {
return mytype{
field1: "abc",
field2: "aaa",
field3: "vvv",
field4: "ddd",
field5: "394834",
field6: "sdfbd34534",
field7: "asdf34534d90sdfsd",
field8: "asdf3424jjiiihiu",
field9: "vmxvbxcvb8rewasdfasdf",
}
}
func returnPointer() *mytype {
return &mytype{
field1: "abc",
field2: "aaa",
field3: "vvv",
field4: "ddd",
field5: "394834",
field6: "sdfbd34534",
field7: "asdf34534d90sdfsd",
field8: "asdf3424jjiiihiu",
field9: "vmxvbxcvb8rewasdfasdf",
}
}
func main() {
}
package main
import (
"fmt"
"testing"
)
func BenchmarkReturnValue(b *testing.B) {
var x mytype
for i := 0; i < b.N; i++ {
x = returnValue()
fmt.Println(x)
}
}
func BenchmarkReturnPointer(b *testing.B) {
var x *mytype
for i := 0; i < b.N; i++ {
x = returnPointer()
fmt.Println(*x)
}
}