doudieheng5322 2018-12-17 03:49
浏览 11
已采纳

使切片大小

In Golang you can allocate memory for a slice with the below syntax :

my_slice := make( []int, 0 )

And then later on I can add elements with the built-in append function as :

my_slice := append(my_slice, 23)

My question is, what's the difference between giving that zero ( or 2 or 5 or whatever) when "making" the slice if later on we can keep adding items as long as we wan?

Is there a performance bonus by trying to guess the capacity that slice will end up having?

  • 写回答

2条回答 默认 最新

  • doutou6803 2018-12-17 04:04
    关注

    The difference is that the memory for the slice is allocated upfront and len(mySlice) returns the total slice length.

    Performance wise it is beneficial to allocate the size upfront because when you call a = append(a, n) the following occurs:

    • It calls the builtin append function and for that it first copies the a slice (slice header, backing array is not part of the header), and it has to create a temporary slice for the variadic parameter which will contain the value n.

    • Then it has to reslice a if it has enough capacity like a = a[:len(a)+1] - which involves assigning the new slice to a inside the append function. If a would not have big enough capacity to do the append "in-place" then a new array would have to be allocated, content from slice copied, and then the assign / append be executed.

    • Then assigns n to a [len(a)-1].

    • Then returns the new slice from the append function, and this new slice is assigned to the local variable a.

    Compared to a[i] = n which is a simple assignment.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line