Home > Article > Backend Development > Is Slice Assignment Always Faster Than Slice Append in Go?
Performance Comparison: Slice Append vs Assign in Go
When working with slices in Go, operations such as appending and assigning elements can have significant performance implications. Two common methods for slice append are available:
append(slice, value): This function creates a new slice with an extended capacity to accommodate the new element and copies the existing elements to the new slice.
slice[index] = value: This assignment directly modifies the element at the specified index of the slice without creating a new copy.
To compare the performance of these two approaches, the following two benchmark functions were created:
func BenchmarkSliceAppend(b *testing.B) { a := make([]int, 0, b.N) for i := 0; i < b.N; i++ { a = append(a, i) } } func BenchmarkSliceSet(b *testing.B) { a := make([]int, b.N) for i := 0; i < b.N; i++ { a[i] = i } }
The results show that slice[index] = value is significantly faster than append(slice, value):
BenchmarkSliceAppend-4 200000000 7.87 ns/op 8 B/op 0 allocs/op BenchmarkSliceSet-4 300000000 5.76 ns/op 8 B/op
Understanding the Performance Difference
Why is slice assignment faster than slice append? The key difference lies in the fact that assignment is a simple in-place operation that modifies the existing slice without requiring any copies or reallocation.
On the other hand, the append function involves several steps:
Even if some of these steps are optimized or inlined, the need to update the local slice variable in each loop iteration adds computational overhead compared to the simpler assignment operation.
The above is the detailed content of Is Slice Assignment Always Faster Than Slice Append in Go?. For more information, please follow other related articles on the PHP Chinese website!