dongqing7789 2014-07-02 20:09
浏览 26

什么时候应该初始化一个新变量,什么时候不应该初始化?

I'm looking at the code examples sql.query and i'm a bit confused by the way the variables are initialized. As far as I understand the var keyword initialize the variable but if you already have a such variable it's better to 'reuse' it instead to reinitialize it. I'm aware that I might have misunderstood the golang specs so I hope this question would help me (and perhaps other folks) get it right.

  rows, err := db.Query("SELECT name FROM users WHERE age=?", age)
    if err != nil {
            log.Fatal(err)
    }
    defer rows.Close()
    for rows.Next() {
            var name string
            if err := rows.Scan(&name); err != nil {
                    log.Fatal(err)
            }
            fmt.Printf("%s is %d
", name, age)
    }
    if err := rows.Err(); err != nil {
            log.Fatal(err)
    }

Why is the "name" variable initialized within the loop and not outside the loop ? (see below). Isn't it less performant to reinitialize it on each loop ?

//how I would do this
  rows, err := db.Query("SELECT name FROM users WHERE age=?", age)
    if err != nil {
            log.Fatal(err)
    }
    defer rows.Close()
    var name string //outside the loop
    for rows.Next() {

            if err := rows.Scan(&name); err != nil {
                    log.Fatal(err)
            }
            fmt.Printf("%s is %d
", name, age)
    }
    if err := rows.Err(); err != nil {
            log.Fatal(err)
    }

or even better use a pointer

      rows, err := db.Query("SELECT name FROM users WHERE age=?", age)
        if err != nil {
                log.Fatal(err)
        }
        defer rows.Close()
        name := new(string) //pointer outside the loop
        for rows.Next() {

                if err := rows.Scan(name); err != nil {
                        log.Fatal(err)
                }
                fmt.Printf("%s is %d
", name, age)
        }
        if err := rows.Err(); err != nil {
                log.Fatal(err)
        }
  • 写回答

1条回答 默认 最新

  • dongyi1159 2014-07-03 07:01
    关注

    Unless you have determined that the allocation is a performance bottleneck, I wouldn't consider such a premature optimisation. After all, it might not even make a difference, so it is best to err on the side of readability/maintainability.

    In general, I'd suggest using the smallest scope for your variables that makes sense. If they are stack allocated, then they will be quite cheap -- assuming space is available, it probably just involves initialising the variable to zero or its initial value. Stack allocated variables scoped within a loop will probably end up with the same memory location each time through the loop too, so there isn't much to be gained from moving them out.

    With that said, it isn't always obvious when a variable will be allocated on the stack. If the compiler decides that the pointer passed to row.Scan could possibly be retained past the function call (that is, it escapes), then name will be allocated on the heap even though it has been defined with var.

    Similarly if the escape analysis determines that the variable doesn't escape, the version that creates the string variable with new may decide to place it on the stack.

    评论

报告相同问题?

悬赏问题

  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥60 许可证msc licensing软件报错显示已有相同版本软件,但是下一步显示无法读取日志目录。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系