简洁地复制一个切片? [英] Concisely deep copy a slice?

查看:92
本文介绍了简洁地复制一个切片?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Go中,深度复制切片的简洁/良好表现方式是什么?我需要将切片复制到新的后备数组中,因为另一个数组由另一个数组拥有,并且可以在复制后进行修改。



我正在做它像这样:

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

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆