Search code examples
godeep-copy

Concisely deep copy a slice?


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.


Solution

  • 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.

    BenchmarkCopy            100000 18240 ns/op
    BenchmarkAppend          100000 18276 ns/op
    BenchmarkAppendPreCapped 100000 16407 ns/op
    

    BenchmarkAppendPreCapped is likely avoiding zeroing and/or growing of the slice. It looks like so:

    copy := append(make([]T, 0, len(orig)), orig...)