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:
-
This calls the builtin
append()function. For that, it first has to copy theaslice (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 valuei. -
Then it has to reslice
aif it has enough capacity (it has in your case) likea = a[:len(a)+1]– which involves assigning the new slice toainside theappend().
(Ifawould 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.) -
Then assigns
itoa[len(a)-1]. -
Then returns the new slice from
append(), and this new slice is assigned to the local variablea.
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’