1
votes

I know about factor and when we exceed some length of underlying array it stops doubling (the length should be at least 512 elements according to recent implementation in go 1.18), my question is why an array is not doubled in the below example where length is much less:

    sl := make([]int, 5, 5)
    sl = append(sl, 6)
    sl = append(sl, 7)
    sl = append(sl, 8)
    sl = append(sl, 9)
    sl = append(sl, 10)
    sl = append(sl, 11)
    fmt.Println(len(sl), cap(sl)) // 10 20 - as expected

    sl2 := make([]int, 5, 5)
    sl2 = append(sl2, 6, 7, 8, 9, 10, 11)
    fmt.Println(len(sl2), cap(sl2)) // 11 12 - why 12 here?
Maybe because doubling the capacity would not be sufficient? - mkrieger1
This is an implementation detail. The specification only requires extending the capacity at least to accomodate the appendable elements, but not how much further it should extend. - icza
@icza not sure whether got your point. Why then sl2 := make([]int, 4, 4) sl2 = append(sl2, 6) doubles underlying array if it is enough to have less capacity to accomodate appendable elements - sprutex
Again: the spec does not require doubling the capacity, it also doesn't require not doubling the capacity. The spec only requires to increase the capacity at least to accomodate the appendable elements. The implementation usually increases it more, to allow room for future growth, to possibly reduce reallocations. But this is an implementation detail, which may change from version to version, from OS to OS etc. - icza