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])
}
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