Efficient Deep Copying of Slices
In Go, creating a deep copy of a slice involves replicating its contents into a separate memory location. This ensures that any modifications made to one slice do not affect the other.
One approach to deep copying is through the append function:
copy := append([]T{}, orig...)
Here, the original slice orig is appended to an empty slice, creating a new slice copy with its own backing array.
An alternative method employs the built-in copy function:
cpy := make([]T, len(orig)) copy(cpy, orig)
This approach directly copies the elements from orig to a newly created slice cpy.
Both solutions effectively copy the values in the slice. However, it's important to note that if the slice contains pointers or structs with pointer fields, these pointer values will still refer to the same locations as in the original slice.
Benchmarking the two methods yields comparable performance:
BenchmarkCopy 100000 24724 ns/op BenchmarkAppend 100000 24967 ns/op
The assembly code reveals that both append and copy likely perform memory zero-filling as part of their operations.
Ultimately, the choice between the append and copy methods depends on individual preferences and performance considerations. However, both approaches effectively deep copy slices, ensuring data integrity when working with separate instances of slice data.
The above is the detailed content of Go Slices: Append vs. Copy for Deep Copying – Which is More Efficient?. For more information, please follow other related articles on the PHP Chinese website!