doutu1939 2014-12-23 14:12
浏览 28

结构切片与结构指针的切片

I often work with slices of structs. Here's an example for such a struct:

type MyStruct struct {
    val1, val2, val3    int
    text1, text2, text3 string
    list                []SomeType
}

So I define my slices as follows:

[]MyStruct

Let's say I have about a million elements in there and I'm working heavily with the slice:

  • I append new elements often. (The total number of elements is unknown.)
  • I sort it every now and then.
  • I also delete elements (although not as much as adding new elements).
  • I read elements often and pass them around (as function arguments).
  • The content of the elements themselves doesn't get changed.

My understanding is that this leads to a lot of shuffling around of the actual struct. The alternative is to create a slice of pointers to the struct:

[]*MyStruct

Now the structs remain where they are and we only deal with pointers which I assume have a smaller footprint and will therefore make my operations faster. But now I'm giving the garbage collector a lot more work.

  • Can you provide general guidelines of when to work with structs directly vs. when to work with pointers to structs?
  • Should I worry about how much work I leave to the GC?
  • Is the performance overhead of copying a struct vs. copying a pointer negligible?
  • Maybe a million elements is not much. How does all of this change when the slice gets much bigger (but still fits in RAM, of course)?
  • 写回答

2条回答 默认 最新

  • dqkxo44488 2014-12-23 14:20
    关注

    Can you provide general guidelines of when to work with structs directly vs. when to work with pointers to structs?

    No, it depends too much on all the other factors you've already mentioned.

    The only real answer is: benchmark and see. Every case is different and all the theory in the world doesn't make a difference when you've got actual timings to work with.

    (That said, my intuition would be to use pointers, and possibly a sync.Pool to aid the garbage collector: http://golang.org/pkg/sync/#Pool)

    评论

报告相同问题?

悬赏问题

  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题