Concisely deep copy a slice?

前端 未结 3 885
粉色の甜心
粉色の甜心 2020-12-17 17:11

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 ma

3条回答
  •  时光取名叫无心
    2020-12-17 17:45

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

提交回复
热议问题