简洁地复制一个切片? [英] Concisely deep copy a slice?
本文介绍了简洁地复制一个切片?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在做它像这样:
copy:= append([] T {},orig ...)
其中T
是元素类型orig
。解决方案看起来最快的方法是追加切片并留下必要的空间。我已经扩展了@Anisus的基准测试结果以及由此产生的最快解决方案。
BenchmarkCopy 100000 18240 ns / op
BenchmarkAppend 100000 18276 ns / op
BenchmarkAppendPreCapped 100000 16407 ns / op
BenchmarkAppendPreCapped很可能避免切片的调零和/或增长。它看起来像这样:
copy:= append(make([] T,0,len(orig)),orig。 ..)
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 oforig
.解决方案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...)
这篇关于简洁地复制一个切片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文