dongliu5475 2018-08-19 23:58
浏览 81

嵌套数组结构的指针或无指针之间的混淆

I have read some of the stack overflow question related to "why pointer and why not pointer", but I could not understand much.

So, want to understand based on my example below

I have a list of users and I am finding a hard time to understand which approach is better and faster for the purpose of nesting array struct of users inside another struct.

For an example -

type loc struct {
    Type string
    Point []float64
}

type User struct {
    ID string
    Name string
    Location loc
    ... // 30 more fields
}

Case A - Using pointer for nested array struct

type Games struct {
    ID string
    Owner []*User
    Player []*User
}

// and storing it as

G:= Games{
    ID: "1",
    Owner: []*User{
        &User {
            ID: "2",
            Name: "User A",
        },
    },
}

Case B - Should I use above approach or below approach to

type Games struct {
    ID string
    Owner []User
    Player []User
}

// storing it as

G := Games {
    ID: "1",
    Owner: []User{
        {
            ID: "2",
            Name: "User A",
        },
    },
}

Considering the situation, I do not have to change data for Owner or Player after creating value for Games above and Player can sometimes remain Nil, should I use only User or it's better to use *User

I have following confusion based on above 2 cases

  • Performance - which one is better & why?
  • Garbage Collection - which one is better & why?
  • Any Memory effects?
  • Any other effects!

Please help me out understanding based on the above example, which method would you have chosen above and why?

  • 写回答

1条回答 默认 最新

  • drl57959 2018-08-21 00:15
    关注

    use option B

    but if you want avoid allocation during iterations or change the content, you need to do it like this:

     for i:=range G.Games{
           G.Games[i]....
     }
    

    this way a copy will be created in every iteration

    for _,game:=range G.Games{
          game....
     }
    

    this looks like premature optimization. write in the most simple/readable way and if is not fast enough, take a look at this in order to find the bottleneck

    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?