When working with slices in Go, you may encounter the need to deep copy a slice, ensuring that changes to the copy do not affect the original slice. This article explores two concise and well-performing methods for achieving this.
One established technique is to use the append function:
copy := append([]T{}, orig...)
However, an alternative method using the built-in copy function has emerged:
cpy := make([]T, len(orig)) copy(cpy, orig)
The documentation for the copy function states that it copies elements from a source slice to a destination slice, overlapping if necessary. It returns the number of elements copied, which is limited by the lengths of both slices.
Note: Both methods copy only the values in the slice. If the slice contains pointers or structs with pointer fields, these pointers will continue to point to the same values as in the original slice.
Benchmark Results:
To assess the performance of these methods, a benchmark was conducted:
BenchmarkCopy 100000 24724 ns/op BenchmarkAppend 100000 24967 ns/op
As you can see, both approaches have very similar performance.
Assembly Analysis:
Examining the assembly generated for each method reveals that both call either runtime.growslice or runtime.makeslice, which are likely responsible for performing any zero-filling required for the new slice.
The above is the detailed content of What are the Most Concise and Performant Ways to Deep Copy Slices in Go?. For more information, please follow other related articles on the PHP Chinese website!