转到:内置的功能-容量是否有所不同

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 < 5; i++ {
    sl = append(sl, "abc")
}

(2) Slice with initial length set, no capacity

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

(3) Slice with initial length set, capacity given

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

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

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.