Avatar ·

Efficient string concatenation in Go: how to correctly and quickly join strings

Hello everyone! I just started learning Go and encountered a performance problem when working with strings. I need to assemble a large HTML report from many fragments. Initially, I simply used the `+` operator: ```go var result string for i := 0; i < 100000; i++ { result += fmt.Sprintf("
%d
", i) } ``` This code runs very slowly and consumes a lot of memory. I read that strings in Go are immutable, and each `+` operation creates a new string, copying the old data. For 100,000 iterations, this leads to enormous overhead. I tried using `strings.Join`, but it only works with slices of strings, and I need to dynamically add elements in a loop. I've also heard about `bytes.Buffer` and `strings.Builder`. Which of these approaches is the most correct and efficient?