Sobes.tech
Junior

What happens when strings are concatenated in Go?

sobes.tech AI

Answer from AI

When concatenating strings in Go, a new string is created containing the concatenation of the original strings. Since strings in Go are immutable, the existing string is not modified.

This can be inefficient when concatenating a large number of strings in a loop, as a new string is created and data is copied on each iteration.

For more efficient string concatenation, especially in loops, it is recommended to use strings.Builder.

// Inefficient example of string concatenation
func inefficientConcat(strs []string) string {
	result := ""
	for _, s := range strs {
		result += s // Creates a new string on each iteration
	}
	return result
}
// Efficient example of string concatenation using strings.Builder
import "strings"

func efficientConcat(strs []string) string {
	var builder strings.Builder
	for _, s := range strs {
		builder.WriteString(s) // Writes to buffer without creating intermediate strings
	}
	return builder.String() // Gets the final string from the buffer
}
Concatenation method Efficiency with large number of strings Note
+ operator Low Creates new strings on each iteration
strings.Join High Optimized for joining string slices
strings.Builder High Suitable for concatenating strings in loops

strings.Join is also an efficient way to concatenate a slice of strings:

import "strings"

func joinConcat(strs []string) string {
	return strings.Join(strs, "") // Efficient concatenation of string slice
}