0PricingLogin
Go Academy · Lesson

strings.Builder

Build strings efficiently.

The Cost of + Concatenation

Because strings are immutable, every s = s + part creates a brand new string and copies all the bytes again.

In a loop this becomes slow and wastes memory.

package main

import "fmt"

func main() {
    s := ""
    for i := 0; i < 3; i++ {
        s = s + "go "
    }
    fmt.Println(s)
}

Meet strings.Builder

strings.Builder grows an internal buffer and avoids repeated copying. You write into it, then read the result once at the end.

Declare one with var b strings.Builder.

package main

import (
    "fmt"
    "strings"
)

func main() {
    var b strings.Builder
    b.WriteString("Hello")
    fmt.Println(b.String())
}

All lessons in this course

  1. Runes vs Bytes
  2. strings Package Functions
  3. strings.Builder
  4. Unicode and utf8
← Back to Go Academy