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.

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

报告相同问题?

悬赏问题

  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用