Sobes.tech
Senior

func fn() { str := "" for i := 0; i < 100000; i++ { str += fmt.Sprintf("%d", i) } fmt.Println(str) }

sobes.tech AI

Answer from AI

In this code, string concatenation is performed in a loop using the += operator, which is inefficient in Go because strings are immutable, and each time a new string is created by copying the old one and adding the new part. This leads to a large number of allocations and reduced performance.

It is better to use strings.Builder for efficient string building:

func fn() {
    var builder strings.Builder
    for i := 0; i < 100000; i++ {
        builder.WriteString(fmt.Sprintf("%d", i))
    }
    fmt.Println(builder.String())
}

strings.Builder accumulates data in a buffer and minimizes the number of allocations, which significantly speeds up execution and reduces garbage collector load.

func fn() { str := "" for i := 0; i < 100000; i++ {… - sobes.tech