append - Capacity of slices in Go -
i have question below code
package main import "fmt" func main() { var []int printslice("a", a) // append works on nil slices. = append(a, 0) printslice("a", a) // slice grows needed. = append(a, 1) printslice("a", a) // can add more 1 element @ time. = append(a, 2, 3, 4) printslice("a", a) } func printslice(s string, x []int) { fmt.printf("%s len=%d cap=%d %v\n", s, len(x), cap(x), x) }
i guess result of running piece of code run code , check if guess correct. code resulted little bit different guess:
result:
on local go tour server:
a len=0 cap=0 [] len=1 cap=1 [0] len=2 cap=2 [0 1] len=5 cap=6 [0 1 2 3 4]
everything ok until last line don't
cap=6
why not
cap=5
my opinion did not create slice explicit capacity therefore system gave value of 6.
2) when tried same code on golang tour server little more diffferent result :
a len=0 cap=0 [] len=1 cap=2 [0] len=2 cap=2 [0 1] len=5 cap=8 [0 1 2 3 4]
what cap=2 on second line , cap=8 on last line?
this question isn't exact duplicate, answer here answers this.
tl;dr — how capacity of slice expanded isn't mentioned in specification , different versions of go (or different implementations, or same version on different architectures, etc.) can expand slice different amounts.
the reason might want make capacity larger need because underneath slice there array immutable (it can't expanded). when "grow" slice happens make new (longer) array, copy values over, , set backing array slice. if appending lots of values, you'd have lots , lots of copies (one every single value), slow, instead runtime allocates more space thinks need has make copies less often.
Comments
Post a Comment