douyi0219 2019-03-03 02:27
浏览 21

如果我知道许多tmp切片的最大大小,那么在创建它们时是否应该设置容量?

If I need to use tmp slices in a function and the function will be called many times, their max capacity will not exceed 10. But the length of them are varied. Just for example, maybe 80% of them only have size of 1. 10% of them have size 3 and 10% of them have size 10.

I can think of an example function like the following:

func getDataFromDb(s []string) []string {
    tmpSlice := make([]string, 0, 10)
    for _, v := range s {
        if check(v) {
            tmpSlice = append(tmpSlice, v)
        }
    }
    ......
    return searchDb(tmpSlice)
}

So should I do var tmpSlice []string, tmpSlice := make([]string, 0, 0), tmpSlice := make([]string, 0, 5), or tmpSlice := make([]string, 0, 10)? or any other suggestions?

  • 写回答

3条回答 默认 最新

  • doubi4814 2019-03-03 02:39
    关注

    I would do

    var tmpSlice []string
    

    This would give you an empty string slice and you can append as needed. Unless the slice range gets big and you know the dimension beforehand, otherwise I wouldn't pre-allocate memory for it

    评论

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭