Junior
How to efficiently concatenate strings in Go?
sobes.tech AI
Answer from AI
Effective methods:
-
+=: Least efficient for multiple concatenations due to creating new strings at each iteration. -
strings.Join: Ideal for joining a slice of strings with a separator. -
fmt.Sprintf: Convenient for formatting, but may be slower than other methods for simple concatenations. -
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
bytes.Buffer: Similar tostrings.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:
+orfmt.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.