gpt4 book ai didi

performance - 在结构 "functions"中使用指针与复制

转载 作者:IT王子 更新时间:2023-10-29 00:50:29 25 4
gpt4 key购买 nike

我是 Go 的新手,在编写结构“函数”时我真的无法决定何时使用指针还是副本(这是正确的术语吗?)

type Blah struct {
c complex128
s string
f float64
}

func (b * Blah) doPtr() {
fmt.Println(b.c, b.s, b.f);
}

func (b Blah) doCopy() {
fmt.Println(b.c, b.s, b.f);
}

现在,我的 C++ 背景告诉我 doPtr 在速度和内存方面都更高效,但是很多示例使用 doCopy 除非你正在修改对象,所以我错过了什么吗?

最佳答案

[Go] Frequently Asked Questions (FAQ)

Should I define methods on values or pointers?

For types such as basic types, slices, and small structs, a value receiver is very cheap so unless the semantics of the method requires a pointer, a value receiver is efficient and clear.

对于性能问题,请勿猜测。运行基准测试。例如,

文件:bench_test.go

package main

import (
"testing"
)

type Blah struct {
c complex128
s string
f float64
}

func (b *Blah) doPtr() {
}

func (b Blah) doCopy() {
}

func BenchmarkDoPtr(b *testing.B) {
blah := Blah{}
for i := 0; i < b.N; i++ {
(&blah).doPtr()
}
}

func BenchmarkDoCopy(b *testing.B) {
blah := Blah{}
for i := 0; i < b.N; i++ {
blah.doCopy()
}
}

输出:

$ go test -bench=.
testing: warning: no tests to run
PASS
BenchmarkDoPtr 2000000000 1.26 ns/op
BenchmarkDoCopy 50000000 32.6 ns/op
ok so/test 4.317s
$

关于performance - 在结构 "functions"中使用指针与复制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22685062/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com