Home > other >  Capacity of slice doubles
Capacity of slice doubles

Time:10-06

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

CodePudding user response:

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.

  • Related