Golang初学者对函数返回值还是指针的测试

先把简单的代码贴出来,然后再废话。

先是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)
	}

}

 

 

转载于:https://my.oschina.net/kylidboy/blog/760972

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值