Go

strings.Builder — Efficient Concatenation

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Building strings with `+` allocates O(n²) memory. `strings.Builder` writes to an internal buffer with a single final allocation — orders of magnitude faster in loops.
Go
Raw
package main

import (
    "fmt"
    "strings"
)

func badJoin(parts []string) string {
    s := ""
    for _, p := range parts {
        s += p + ","                              // O(n²) — allocates each iteration
    }
    return s
}

func goodJoin(parts []string) string {
    var b strings.Builder
    b.Grow(len(parts) * 16)                       // optional preallocation
    for i, p := range parts {
        if i > 0 { b.WriteByte(',') }
        b.WriteString(p)
    }
    return b.String()
}

// Even simpler when you have a slice — strings.Join is built for this
func bestJoin(parts []string) string {
    return strings.Join(parts, ",")
}

func main() {
    parts := []string{"a", "b", "c", "d"}
    fmt.Println(goodJoin(parts))                  // a,b,c,d
    fmt.Println(bestJoin(parts))                  // a,b,c,d
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.