Golang slice append vs assign performance

a[i] = i simply assigns the value i to a[i]. This is not appending, it’s just a simple assignment.

Now the append:

a = append(a, i)

In theory the following happens:

  1. This calls the builtin append() function. For that, it first has to copy the a slice (slice header, backing array is not part of the header), and it has to create a temporary slice for the variadic parameter which will contain the value i.

  2. Then it has to reslice a if it has enough capacity (it has in your case) like a = a[:len(a)+1] – which involves assigning the new slice to a inside the append().
    (If a would not have big enough capacity to do the append “in-place”, a new array would have to be allocated, content from slice copied, and then the assign / append be executed – but it is not the case here.)

  3. Then assigns i to a[len(a)-1].

  4. Then returns the new slice from append(), and this new slice is assigned to the local variable a.

A lot of things happen here compared to a simple assignment. Even if many of these steps are optimized and / or inlined, as a minimum addition to assigning i to an element of the slice, the local variable a of slice type (which is a slice header) has to be updated in each cycle of the loop.

Recommended reading: The Go Blog: Arrays, slices (and strings): The mechanics of ‘append’

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)