Sobes.tech
Junior

How to efficiently concatenate strings in Go?

sobes.tech AI

Answer from AI

Effective methods:

  1. +=: Least efficient for multiple concatenations due to creating new strings at each iteration.

  2. strings.Join: Ideal for joining a slice of strings with a separator.

  3. fmt.Sprintf: Convenient for formatting, but may be slower than other methods for simple concatenations.

  4. strings.Builder: Most efficient for building long strings from many fragments, avoiding unnecessary allocations.

// Example with strings.Builder
import "strings"

var builder strings.Builder
builder.WriteString("Hello")
builder.WriteString(" ")
builder.WriteString("World")
result := builder.String() // Getting the resulting string
  1. bytes.Buffer: Similar to strings.Builder, but works with byte slices. Efficient when working with data that doesn't necessarily need to be UTF-8 strings.
// Example with bytes.Buffer
import "bytes"

var buffer bytes.Buffer
buffer.WriteString("Byte")
buffer.WriteString(" ")
buffer.WriteString("Data")
result := buffer.String() // Getting the resulting string

The choice of method depends on the specific task:

  • Single concatenation: + or fmt.Sprintf.
  • Joining a slice of strings: strings.Join.
  • Building a long string from many fragments in a loop: strings.Builder.
  • Working with bytes: bytes.Buffer.