Home >Backend Development >Golang >Which is Faster: Slice Append or Direct Assignment in Golang?
Performance Comparison of slice append and assign in Golang
In Golang, there are two common ways to append elements to a slice: using the append function or directly assigning values to slice indices. To understand the performance differences between these methods, consider the following code:
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 } }
Benchmark results show that a[i] = i significantly outperforms a = append(a, i) in terms of execution time:
BenchmarkSliceAppend-4 200000000 7.87 ns/op 8 B/op 0 allocs/op BenchmarkSliceSet-4 300000000 5.76 ns/op 8 B/op
Reason for Performance Difference
The performance difference stems from the underlying operations performed by each method. a[i] = i simply assigns the value i to the ith element of the slice, which is a straightforward and efficient operation.
In contrast, a = append(a, i) involves a more complex process:
This additional copying and allocation contributes to the performance overhead of the append method, resulting in a slower execution time compared to the direct assignment.
Conclusion
For appending elements to a slice, a[i] = i is a more efficient option than a = append(a, i) due to its simpler and faster operation. Keep this in mind when optimizing code performance for slice manipulation tasks.
The above is the detailed content of Which is Faster: Slice Append or Direct Assignment in Golang?. For more information, please follow other related articles on the PHP Chinese website!