JT Archie

# Go Slices: Efficiently Append Elements

In Go, slices are a powerful and flexible data structure for handling sequences of values. One common operation is appending elements to a slice. This guide demonstrates how to efficiently append elements to a slice while minimizing memory reallocations.

Consider a simple example where you want to create a slice of integers and append values to it:

package main

import "fmt"

func main() {
    nums := []int{}
    for i := 0; i < 10; i++ {
        nums = append(nums, i)
    }

    fmt.Println(nums)
}

In this example, each call to append might cause a memory reallocation, which can be expensive in terms of performance. To optimize this, you can use the make function to preallocate the underlying array:

By using make with a capacity argument (cap), you allocate enough memory for the underlying array at the beginning, avoiding costly reallocations during the append operation. This can lead to better performance and more efficient memory usage in your Go programs.

package main

import "fmt"

func main() {
    nums := make([]int, 0, 10)
    for i := 0; i < 10; i++ {
        nums = append(nums, i)
    }

    fmt.Println(nums)
}

# Follow for more tips