切片的容量翻倍了。

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

Capacity of slice doubles

问题

我正在学习golang,并在练习中使用以下代码来操作切片:

package main

import "fmt"

func main() {

    var count int
    var subject string
    subjects := make([]string, 0)

    fmt.Print("Enter total number of subjects:")
    fmt.Scan(&count)

    for count != 0 {
        fmt.Print("\n\nEnter subject name: ")
        fmt.Scan(&subject)
        subjects = append(subjects, subject)
        fmt.Printf("\nlen=%d \ncap=%d \n%v\n", len(subjects), cap(subjects), subjects)
        count--
    }

}

以下是我得到的结果:

Enter subject name: physics

len=4 cap=4 [hindi english maths physics]

Enter subject name: geography

len=5 cap=8 [hindi english maths physics geography]

为什么在第5个元素时容量会翻倍,并且如何按正确的顺序增加容量?

英文:

I am learning golang and while practicing slice with following code:

package main

import "fmt"

func main() {

	var count int
	var subject string
	subjects := make([]string, 0)

	fmt.Print("Enter total number of subjects:")
	fmt.Scan(&count)

	for count != 0 {
		fmt.Print("\n\nEnter subject name: ")
		fmt.Scan(&subject)
		subjects = append(subjects, subject)
		fmt.Printf("\nlen=%d \ncap=%d \n%v\n", len(subjects), cap(subjects), subjects)
		count--
	}

}

following is the result, I get:

> Enter subject name: physics
>
> len=4 cap=4 [hindi english maths physics]
>
>
> Enter subject name: geography
>
> len=5 cap=8 [hindi english maths physics geography]

Why does the capacity double on 5th and how to increase capacity in proper order

答案1

得分: 2

“适当的顺序”在这种情况下不适用。Go的切片是由一个数组支持的,当容量达到时,每次追加元素都需要复制该数组。通过创建一个更大容量的数组,Go试图最小化复制操作的次数,从而使append函数更高效。

如果你事先知道元素的数量,可以使用它来设置初始容量:

fmt.Print("输入科目总数:")
fmt.Scan(&count)

subjects := make([]string, 0, count)

除非超过初始容量,否则Go不会增加底层数组的大小。

英文:

The "proper order" is not applicable term in this case. Go slice is backed by an array which needs to be copied every time you append to it when the capacity is reached. By making an array of bigger capacity Go is trying to minimise a number of copy operations and thus make an append function more performant.

If you know a number of elements in advance you can use it to set the initial capacity:

fmt.Print("Enter total number of subjects:")
fmt.Scan(&count)

subjects := make([]string, 0, count)

Go won't grow an underlying array unless you exceed the initial capacity.

huangapple
  • 本文由 发表于 2021年10月5日 17:09:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/69447720.html
匿名

发表评论

匿名网友

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

确定