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条)

报告相同问题?

悬赏问题

  • ¥60 pb数据库修改或者求完整pb库存系统,需为pb自带数据库
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路