Large Collection Copy (ARCH5086)
Ce contenu n’est pas encore disponible dans votre langue.
Key go.performance.large-collection-copy · Severity info · Category performance
Appending to a zero-capacity slice when the final size is known causes repeated reallocation and copying. Preallocate capacity with make.
Incorrect
Section titled “Incorrect”func double(in []int) []int { var out []int for _, n := range in { out = append(out, n*2) } return out}Correct
Section titled “Correct”func double(in []int) []int { out := make([]int, 0, len(in)) for _, n := range in { out = append(out, n*2) } return out}Create the target slice with preallocated capacity via make([]T, 0, len(in)).