Skip to content

关于1.2.3节slice扩容的特殊情况 #2

Description

@marjune163

除了常规的按现有容量×2或×1.25倍,有个特殊情况是如果append新加入的元素超过了按倍数扩容的容量,其实际扩容容量会满足append的需求,经过测试貌似是实际需求容量向上取偶数,测试代码如下:

s:=[]int{1,2,3,4,5,6,7,8}
fmt.Println(len(s),cap(s))      // 8 8

s1:=append(s,9,10,11,12,13,14,15,16)
fmt.Println(len(s1),cap(s1))    // 16 16

s2:=append(s,9,10,11,12,13,14,15,16,17)
fmt.Println(len(s2),cap(s2))    // 17 18

s3:=append(s,9,10,11,12,13,14,15,16,17,18)
fmt.Println(len(s3),cap(s3))    // 18 18

s4:=append(s,9,10,11,12,13,14,15,16,17,18,19)
fmt.Println(len(s4),cap(s4))    // 19 20

s5:=append(s,9,10,11,12,13,14,15,16,17,18,19,20)
fmt.Println(len(s5),cap(s5))    // 20 20

s6:=append(s,9,10,11,12,13,14,16,16,17,18,19,20,21)
fmt.Println(len(s6),cap(s6))    // 21 22

s7:=append(s,9,10,11,12,13,14,17,17,17,18,19,20,21,22)
fmt.Println(len(s7),cap(s7))    // 22 22

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions