Sobes.tech
Senior

// what's wrong with this code? how to improve it? func fn() { str := "" for i := 0; i < 100000; i++ { str += fmt.Sprintf("%d", i) } fmt.Println(str) }

sobes.tech AI

Answer from AI

The problem with this code is that the string str is concatenated in a loop using the += operator. In Go, strings are immutable, so each iteration creates a new string, leading to a large number of allocations and reduced performance.

It is better to use strings.Builder or bytes.Buffer for efficient string accumulation:

import (
    "fmt"
    "strings"
)

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

This will significantly reduce the number of allocations and speed up the code execution.