BudiBadu Logo

Samplebadu

Code with Example
BudiBadu Logo
Samplebadu

Go by Example: Join String

Go 1.23

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.

Code Breakdown

13
Using 'strings.Join'. This takes a slice and a separator. It's highly optimized and should be your default choice for combining lists of strings.
19
Using 'strings.Builder'. We declare 'sb' (zero value is ready to use). We call 'WriteString' to append data. Finally, 'sb.String()' returns the accumulated result.
30
Simple concatenation. For a single line like this, the '+' operator is perfectly fine and readable. The performance penalty only matters in loops or high-throughput code.