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

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

报告相同问题?

悬赏问题

  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥15 键盘指令混乱情况下的启动盘系统重装