In Go, what's a concise/well-performing way to deep copy a slice? I need to copy the slice to a new backing array, because the other array is owned by something else and may be modified after the copy.
I'm currently doing it like this:
copy := append([]T{}, orig...)
where T
is the element type of orig
.
It would seem the fastest way is to append to a slice with the necessary space. I've extended @Anisus answer with the benchmark results, and the resulting fastest solution.
BenchmarkAppendPreCapped is likely avoiding zeroing and/or growing of the slice. It looks like so:
For example,
Output:
References:
Arrays, slices (and strings): The mechanics of 'append'
Benchmarks:
Output:
Not sure which solution is fastest without a benchmark, but an alternative is using the built in
copy
:From the documentation:
Note
The solution will copy all the values in the slice. If the slice contains pointers or structs with pointer fields, these pointer values will still point to the same values as the
orig
slice.Benchmark
Benchmarking the two options, you can see they have very similar performance.
This is the benchmark code:
package main
I am not sure when/if the zero-fill is performed. But if you look at the assembly, in the append version you will have:
while the copy will call:
and I would guess that both of these calls performs the zero-fill.