Go: 内置函数 make – 容量是否有影响

huangapple go评论89阅读模式
英文:

Go: builtin make - does the capacity make a difference

问题

考虑想要动态地填充一个包含恰好5个元素的数组/切片。不多也不少。

#(1) 初始长度为0的切片

sl := []string{}
for i := 0; i < 5; i++ {
    sl = append(sl, "abc")
}

#(2) 初始长度已设置,但没有容量限制的切片

sl := make([]string, 5)
for i := 0; i < 5; i++ {
    sl[i] = "abc"
}

#(3) 初始长度已设置,并指定了容量的切片

sl := make([]string, 5, 5)
for i := 0; i < 5; i++ {
    sl[i] = "abc"
}

我的直觉告诉我,#1 不是最佳解决方案,但我想知道为什么我会选择 #2 而不是 #3,或者反过来?(从性能角度考虑)

英文:

Consider wanting to dynamically fill an array/slice with exactly 5 elements. No more, and no less.

#(1) Slice with initial length 0

sl := []string{}
for i := 0; i &lt; 5; i++ {
    sl = append(sl, &quot;abc&quot;)
}

#(2) Slice with initial length set, no capacity

sl := make([]string, 5)
for i := 0; i &lt; 5; i++ {
    s1[i] = &quot;abc&quot;
}

#(3) Slice with initial length set, capacity given

sl := make([]string, 5, 5)
for i := 0; i &lt; 5; i++ {
    sl[i] = &quot;abc&quot;
}

My feeling tells me that #1 is not the <i>best</i> solution, but I am wondering why I would choose #2 over #3 or vice versa? (performance-wise)

答案1

得分: 3

首先,每当你对性能有疑问时,可以使用 benchmarkprofile

其次,我在这里没有看到任何区别。考虑到这段代码

s := make([]int, 5)
fmt.Println(cap(s))

打印出5,你的第2点和第3点基本上是相同的。

英文:

First of all, whenever you have a question about performance, benchmark and profile.

Secondly, I don't see any difference here. Considering that this code

s := make([]int, 5)
fmt.Println(cap(s))

prints 5, your #2 and #3 are basically the same.

huangapple
  • 本文由 发表于 2015年2月25日 21:12:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/28719934.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定