duanming0494 2015-10-23 09:58
浏览 27
已采纳

在进行中,是否值得避免创建大小为0的切片?

I have a program in which I'm going to make lots and lots of slices, some of which might be empty:

nb := something() // something might return 0
slices = append(slices, make([]int, nb))

Does make([]int, 0) allocates some memory and is, thus, less memory efficient than a nil slice although they share the same behavior ? By how much ?

If so, is it worth doing a test to avoid useless allocations, or is the CPU time cost of the test not worth the saving in memory (or any other reason not to do so) ?

var sl slice
nb := something()
if nb > 0 {
    sl = make([]int, nb)
}
slices = append(slices, sl)
  • 写回答

2条回答 默认 最新

  • douyuan1752 2015-10-23 10:58
    关注

    There is no difference in the allocated memory between

    var a []T // nil slice
    

    and

    a := make([]T, 0) // zero-length, zero-capacity, non-nil slice
    

    The difference is in the slice header content. In the second case the slice pointer contains some fixed address, same for all 0-sized allocations.

    If this code is in a performance critical part of the program, the difference makes ... quite a difference. In the first case you do zero the slice header, in the second case you go through 3-4 function calls, some range checks for cap and length, etc. before malloc returns a pointer to the zero base.

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

报告相同问题?

悬赏问题

  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥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