gomemorysliceallocation

does append empty slice to another slice can process allocation in golang?


i have a small question about 'append' function in golang:

I have a slice1 and a function which calls in for loop and returns some slice2 which can be empty as well. So the question is how golang will process this case if this function will frequently return empty slices: what type of code will be more optimized:

  1. to use check 'if len(slice2) != 0' before doing of append
  2. just append all returned slices to slice1

Does it actually metter which of this two cases to use?

i have tried both cases with empty slices, but i didn't see the difference, maybe i missed something?


Solution

  • A new array is not allocated if no elements are appended:

    From the docs:

    The append built-in function appends elements to the end of a slice. If it has sufficient capacity, the destination is resliced to accommodate the new elements.

    The capacity is always sufficient to accommodate zero new elements, of course.

    You can verify this by comparing the addresses of the first element before and after the append:

    package main
    
    import "fmt"
    
    func main() {
            s := make([]int, 3, 3)
            var empty []int
    
            S := append(s, empty...)
            fmt.Printf("%p\n%p\n", &s[0], &S[0])
    }
    // Output:
    // 0xc00001a018
    // 0xc00001a018
    

    Try it on the playground: https://go.dev/play/p/PYnnsN-2PMn