Dig101 — Go string layout, `+` lowering, and concat benchmarks

Contents

  1. 1. 0x01 How + is lowered
  2. 2. 0x02 String is slice-shaped
  3. 3. 0x03 Strings are immutable
  4. 4. 0x04 Conversions
    1. 4.1. rune → string
    2. 4.2. []byte → string
    3. 4.3. string → []rune
    4. 4.4. string → []byte
  5. 5. 0x05 Zero-copy []byte → string
  6. 6. 0x06 Concat benchmarks

Dig101: dig more, simplify more, know more.

Strings look simple. They mostly are—start with what the compiler does for +.

0x01 How + is lowered

1
2
3
4
5
s1 := "x"
s2 := s1 + "y" + "x" + "z"
s3 := s1 + "y" + s1 + "z" + s1
s4 := s1 + "y" + s1 + "z" + s1 + "z"
println(s2, s3, s4)

go tool compile -m folds literal runs:

1
2
3
4
5
$ go tool compile -m  plus.go
plus.go:21:6: can inline plus
plus.go:23:11: s1 + "yxz" does not escape
plus.go:24:28: s1 + "y" + s1 + "z" + s1 does not escape
plus.go:25:33: s1 + "y" + s1 + "z" + s1 + "z" does not escape

Assembly (-S | grep concat):

1
2
3
4
5
6
7
$ go tool compile -S  plus.go|grep concat
0x0068 00104 (plus.go:20) CALL runtime.concatstring2(SB)
0x00eb 00235 (plus.go:21) CALL runtime.concatstring5(SB)
0x01e1 00481 (plus.go:22) CALL runtime.concatstrings(SB)
rel 105+4 t=8 runtime.concatstring2+0
rel 236+4 t=8 runtime.concatstring5+0
rel 482+4 t=8 runtime.concatstrings+0

Pipeline:

  • Fold constant string fragments at compile time ("y" + "x" + "z" → "yxz").
  • Pass remaining operands to concatstringN / concatstrings.
  • Arity 2–5 → concatstring2…concatstring5; more → slice concatstrings.
  • Total length < 32 → stack tmpBuf to skip a heap alloc.

Call sites in the compiler and runtime:

1
2
3
4
5
6
7
8
9
10
// cmd/compile/internal/gc/walk.go addstr
// runtime/string.go concatstrings

// Small-string scratch on stack
const tmpStringBufSize = 32
type tmpBuf [tmpStringBufSize]byte

func concatstrings(buf *tmpBuf, a []string) string
func concatstring2(buf *tmpBuf, a [2]string) string
...

0x02 String is slice-shaped

Inside concatstrings you already see slice mechanics:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
func concatstrings(buf *tmpBuf, a []string) string
...
s, b := rawstringtmp(buf, l)
for _, x := range a {
copy(b, x)
b = b[len(x):]
}
...
}

func rawstringtmp(buf *tmpBuf, l int) (s string, b []byte) {
if buf != nil && l <= len(buf) {
b = buf[:l]
s = slicebytetostringtmp(b)
} else {
s, b = rawstring(l)
}
return
}

type stringStruct struct {
str unsafe.Pointer
len int
}

func rawstring(size int) (s string, b []byte) {
p := mallocgc(uintptr(size), nil, false)

stringStructOf(&s).str = p
stringStructOf(&s).len = size

// Reuse slice header layout
*(*slice)(unsafe.Pointer(&b)) = slice{p, size, size}

return
}

*(*slice)(unsafe.Pointer(&b)) = slice{p, size, size} — same pointer/len/cap as a []byte with len == cap.

0x03 Strings are immutable

1
2
3
4
5
6
s:="abc"
// Rebind to new constant data
s="xyz"
// Cannot mutate bytes in place
s[0]='b'
// Error: cannot assign to s[0]

Local edits go through []byte or []rune:

1
2
3
4
5
6
7
8
9
10
s := "ab\xe9" // UTF-8 for ab + e-acute
// 1. byte edit
bs := []byte(s)
bs[0] = 'x'
println(string(bs))

// 2. rune edit
rs := []rune(s)
rs[2] = 'o'
println(string(rs))

0x04 Conversions

rune → string

rune is int32 (Unicode code point). Build []byte via encoderune into p.

Bounds-check hints like _ = p[1] help the compiler: bounds check elimination.

[]byte → string

Copy from slice base + length into a string header.

string → []rune

Allocate []rune, decode runes. for range over a string is like ranging []rune(string); immutability means no race checks on the source bytes.

string → []byte

Allocate and copy.

0x05 Zero-copy []byte → string

Some paths skip copying:

1
2
3
4
5
// Compiler may optimize string(b) in map keys, compares, etc.
func slicebytetostringtmp(b []byte) string {
...
return *(*string)(unsafe.Pointer(&b))
}

Reinterpret the slice header as a string. Do not mutate b afterward—you would break immutability. strings.Builder.String() exploits this for speed.

0x06 Concat benchmarks

Short (16 B) vs long (256 B) strings, few vs many joins: concat_benchmark.

sprint/sprintf/Join builds are pre-sized lists; +, Builder, Buffer loop and append.

String concat benchmark before Grow tuning

  • Prebuilt args: sprint ≈ sprintf; strings.Join wins (uses Builder internally).
  • Looping +: cost grows quickly with count.
  • Few joins: strings.Builder beats bytes.Buffer; many joins the gap flips—check alloc counts.

Builder did more allocations per op in the test because Reset() drops storage:

1
2
3
4
5
6
7
8
9
10
11
// Reset keeps backing array for reuse
func (b *Buffer) Reset() {
b.buf = b.buf[:0]
b.off = 0
b.lastRead = opInvalid
}
// Reset clears everything — Builder.String() is zero-copy from its slice
func (b *Builder) Reset() {
b.addr = nil
b.buf = nil
}

Builder forbids aliasing after String() (copyCheck). Both types benefit from one upfront Grow—see concatIterWithGrowInit in the repo.

After Grow, alloc counts drop to 1 per op and Builder leads, matching the docs.

String concat benchmark after Grow init

Sample code: NewbMiao/Dig101-Go/types/string

Questions? Leave a comment below or email: newbvirgil@gmail.com