在GoLang中按值传递或按引用传递更有效?
Let's say I have a struct implementing an interface like below:
type IFace interface {
Method1()
Method2()
Method3()
}
type Face struct {
Prop1 string
Prop2 int
}
// IFace implementation here...
Now if I have method that accepts IFace
is it better to design it to accept a pointer to that interface of value?
- Accept pointer:
func DummyMethod(f *IFace) {
(*f).Method1()
}
- By value:
func DummyMethod(f IFace){
f.Method1()
}
My first guess is since these are structs, probably it's better to pass by value? Or is there a rule of thumb considering the size and nature of the struct when to start passing a pointer?
Also, when we are adding methods to a struct is it better to pass a pointer to the struct or it's value?
假设我有一个结构,实现了如下所示的接口: p>
类型IFace接口{ Method1() Method2() Method3() } type Face struct { Prop1字符串 Prop2 int } //此处是IFace的实现... code> pre>现在,如果我有接受
IFace code>的方法,最好将它设计为接受指针 p>
- 接受指针: li> ol>
func DummyMethod(f * IFace){ (* f).Method1() } code> pre>
- 按值: li> ol>
func DummyMethod(f IFace){ f.Method1() } code> pre>
我的第一个猜测是,由于这些是结构,因此最好通过值传递? 还是有经验法则考虑何时开始传递指针的结构的大小和性质? p>
此外,当我们向结构添加方法时,传递指针更好 到结构或它的值? p> div>
When passing interface type as a parameter, pass it by value, note that interface type itself would be a pointer to concrete type.
When it comes to the performance side, using interface comes with the price too, it simply cannot be inlined.
I guess it is fine to use interface with dozen calls per request/entry point, but if an app has to make thousands+ invocations, benchmark your code first before making a call.