douyoupingji7238 2015-07-17 16:08
浏览 54
已采纳

Go语言:重复的字符串常量编译

I'm considering writing a template to Go code generator and wonder:

If I have many string constants and/or variables with the same value would they be stored in an executable file multiple times or compiler will make an optimisation and store just 1 instance per duplicate and refer it wherever needed?

E.g.

File1.go
========
s1 := "some_string_1"
s2 := "some_string_2"

FileN.go
========
a1 := "some_string_1"
a1 := "some_string_2"

Would it affect file size if I have multiple files with the same constants or compiler is smart enough to make optimization?

Imagine that in many templates I have somthing like:

Template 1
==========
{% for a in list1 %}<td>{{a}}</td>{% endfor %}

Tempalte 2
==========
{% for b in list2 %}<td>{{b.c}}</td><td>{{b.d}}</td>{% endfor %}

that would be translated to something like:

for i, a := range list {
    write("<td>")
    write(a)
    write("</td>")
}

for i, b := range list2 {
    write("<td>")
    write(b.c)
    write("</td></td>")
    write(b.d)
    write("</td>")
}

Obviously the <td> & </td> would be repeated many times in code. So would it make any sense to create a global array of strings and takes values from it? Something like:

myStrings := [...]string{
    "<td>",
    "</td>"
}
for i, a := range list {
    write(myStrings[0])
    write(a)
    write(myStrings[1])
}
  • 写回答

1条回答 默认 最新

  • dongtun3259 2015-07-17 17:49
    关注

    The language spec says nothing regarding the internal storage of string constants or literals. Based on this discussion I would assume there is currently no interning in the language; https://github.com/golang/go/issues/5160 though that is a bit dated now.

    That same search turned up this project which you may find helpful; https://gist.github.com/karlseguin/6570372

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在node.js中或者java中给wav格式的音频编码成sil格式呢
  • ¥15 不小心不正规的开发公司导致不给我们y码,
  • ¥15 我的代码无法在vc++中运行呀,错误很多
  • ¥50 求一个win系统下运行的可自动抓取arm64架构deb安装包和其依赖包的软件。
  • ¥60 fail to initialize keyboard hotkeys through kernel.0000000000
  • ¥30 ppOCRLabel导出识别结果失败
  • ¥15 Centos7 / PETGEM
  • ¥15 csmar数据进行spss描述性统计分析
  • ¥15 各位请问平行检验趋势图这样要怎么调整?说标准差差异太大了
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题