duanlang1196 2014-06-27 12:52
浏览 52
已采纳

指针和struct中的值有什么区别?

Given the following struct:

type Exp struct {
  foo int,
  bar *int
}

What is the difference in term of performance when using a pointer or a value in a struct. Is there any overhead or this just two schools of Go programming?

I would use pointers to implement a chained struct but is this the only case we have to use pointers in struct in order to gain performance?

PS: in the above struct we talk about a simple int but it could be any other type (even custom one)

  • 写回答

2条回答 默认 最新

  • doubeng3216 2014-06-27 14:00
    关注

    Use the form which is most functionally useful for your program. Basically, this means if it's useful for the value to be nil, then use a pointer.

    From a performance perspective, primitive numeric types are always more efficient to copy than to dereference a pointer. Even more complex data structures are still usually faster to copy if they are smaller than a cache line or two (under 128 bytes is a good rule of thumb for x86 CPUs).

    When things get a little larger, you need to benchmark if performance concerns you. CPUs are very efficient at copying data, and there are so many variables involved which will determine the locality and cache friendliness of your data, it really depends on your program's behavior, and the hardware you're using.

    This is an excellent series of articles if you want to better understand the how memory and software interact: "What every programmer should know about memory".

    In short, I tell people to choose a pointer or not based on the logic of the program, and worry about performance later.

    • Use a pointer if you need to pass something to be modified.
    • Use a pointer if you need to determine if something was unset/nil.
    • Use a pointer if you are using a type that has methods with pointer receivers.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?