douyan3478 2014-11-21 06:45
浏览 37
已采纳

简直深深地复制了一片?

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.

  • 写回答

3条回答 默认 最新

  • doucheng2210 2014-11-28 05:44
    关注

    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...)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 基于单片机数字电压表电路组成及框图
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line