dsc56927 2016-07-13 23:17
浏览 16
已采纳

常量在Go中如何工作?

In Go which snippet allocates less objects? Or do they both use the same amount of allocations, if so; why? (:

for i := 0; i < 10000000; i++ {
        log.println("hello")
    }

Does the code below allocates only 1 string?

const (
    HELLO string = "hello"
)

for i := 0; i < 10000000; i++ {
    log.println(HELLO)
}
  • 写回答

2条回答 默认 最新

  • dongyanggan3025 2016-07-14 00:17
    关注

    Here's an adaptation of your program that prints out the underlying string representation in both cases.

    package main
    
    import (
        "fmt"
        "reflect"
        "unsafe"
    )
    
    const (
        Hello string = "hello"
    )
    
    func main() {
        for i := 0; i < 3; i++ {
            a := "hello"
            sh := (*reflect.StringHeader)(unsafe.Pointer(&a))
            fmt.Println(a, " ", *sh)
        }
    
        fmt.Println()
    
        for i := 0; i < 3; i++ {
            a := Hello
            sh := (*reflect.StringHeader)(unsafe.Pointer(&a))
            fmt.Println(a, " ", *sh)
        }
    }
    

    Here's the output:

    hello   {4870353 5}
    hello   {4870353 5}
    hello   {4870353 5}
    
    hello   {4870353 5}
    hello   {4870353 5}
    hello   {4870353 5}
    

    The string header in {} in the output shows a pointer to the character data ("hello"), and the length of the string.

    You can see that the pointer to the string data is the same throughout the program: the bytes data "hello" is referenced at exactly one memory address (here 4870353), no matter the loop count, and no matter whether it's a hardcoded string or a constant.

    The language spec itself makes no guarantees about such behavior, but constant string interning is such a natural optimisation that it would be surprising if go behaved in any significantly different way.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥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 腾讯云如何建立同一个项目中物模型之间的联系