doutucui0133 2018-03-06 03:59
浏览 114
已采纳

预先存储对指针的引用与在移动中引用指针之间的区别

First, hopefully, the question's title makes sense (feel free to suggest edits). I have never dealt with pointers manually before, just learning Go.

So, is doing the following:

func something() {
  something := *thing
  go func() {
    for err := range something.Errors() {
      fmt.Println(err)
    }
  }()
}

...have any advantage over:

func something() {
  go func() {
    for err := range (*thing).Errors() {
      fmt.Println(err)
    }
  }()
}

Note that I have tried doing *thing.Errors() in second case, but it gives me error unless I put braces around it (which is understandable since Errors() method doesn't return any pointers, I guess?).


Although this is micro-optimization that I would normally not care about, but for learning and curiosity purposes, won't the second case have more performance overhead (since its referencing pointer on every iteration)?

What is thing, you ask? Most likely a struct, or could be an interface or could be anything (I know that certain components such as maps, strings, functions, structs etc. are passed by reference by default. But I would still like to know for those components that are not).

  • 写回答

1条回答 默认 最新

  • douzhi1879 2018-03-06 05:25
    关注

    If Errors is in the method set for *thing then you can use for err := range thing.Errors() { ... }.

    Because the range expression is evaluated once at the beginning of the loop, there should be no difference in performance between the two snippets in the question and my suggestion in this answer.

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

报告相同问题?

悬赏问题

  • ¥20 关于php中URL传递GET全局变量的问题
  • ¥15 怎么改成循环输入删除(语言-c语言)
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection
  • ¥15 nginx代理报502的错误
  • ¥100 当AWR1843发送完设置的固定帧后,如何使其再发送第一次的帧
  • ¥15 图示五个参数的模型校正是用什么方法做出来的。如何建立其他模型
  • ¥100 描述一下元器件的基本功能,pcba板的基本原理
  • ¥15 STM32无法向设备写入固件