Go by Example: Join String
Concatenating strings efficiently is crucial. Use `strings.Join` for slices and `strings.Builder` for loops to avoid performance pitfalls.
Code
package main
import (
"fmt"
"strings"
)
func main() {
parts := []string{"Go", "is", "awesome"}
// 1. strings.Join (Best for Slices)
// Efficiently concatenates a slice with a separator.
s1 := strings.Join(parts, " ")
fmt.Println(s1)
// 2. strings.Builder (Best for Loops)
// Use this when building a string incrementally.
// It avoids creating a new string for every '+' operation.
var sb strings.Builder
for i, word := range parts {
sb.WriteString(word)
if i < len(parts)-1 {
sb.WriteString("-")
}
}
fmt.Println(sb.String())
// 3. The '+' Operator (Avoid in Loops)
// Simple concatenation is fine for small, fixed cases.
s3 := "Hello" + " " + "World"
fmt.Println(s3)
}
Explanation
String concatenation in Go requires careful consideration of performance because strings are immutable; every time you add two strings together using the + operator, a new string is allocated and the contents are copied. For joining a known slice of strings, strings.Join is the most efficient method. It calculates the total required memory upfront and performs a single allocation, copying the data rapidly into the result.
When constructing a string incrementally, such as inside a loop or conditional logic, strings.Builder is the standard, high-performance solution. It maintains an internal buffer that grows as needed, allowing you to append text without generating garbage (intermediate string allocations) at every step. Using strings.Builder instead of repeated + operations can lead to orders-of-magnitude performance improvements in hot paths or when processing large amounts of text.
- strings.Join: Use when you already have a slice of strings.
- strings.Builder: Use for incremental building (loops).
- Operator +: Fine for simple, one-off concatenations.

