duanbai1370 2019-02-24 03:31
浏览 135
已采纳

在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?

  1. Accept pointer:
func DummyMethod(f *IFace) {
   (*f).Method1()
}
  1. 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?

  • 写回答

1条回答 默认 最新

  • duanbeng8872 2019-02-24 04:53
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。
  • ¥20 CST怎么把天线放在座椅环境中并仿真