Golang初学者对函数返回值还是指针的测试
发布时间:2020-12-16 18:25:58 所属栏目:大数据 来源:网络整理
导读:先把简单的代码贴出来,然后再废话。 先是benchmark的命令 go test -bench=Poin -memprofile=pointermem.pprof -memprofilerate=1 -benchmem go test -bench=Value -memprofile=valuemem.pprof -memprofilerate=1 -benchmem 然后是pprof的结果,先是pointer
先把简单的代码贴出来,然后再废话。 先是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",} } 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) } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |