Home > database >  Go slices capacity increase rate
Go slices capacity increase rate

Time:02-06

I am new in Go and going through a book called "Learning Go" publised by O'reilly. While reading about Slices, there is a statement below:

"To increase the size of a slice, as of Go 1.14 the rule is that it doubles the capacity until reaching the size of 1024 and then grow by 25 % afterwards." I wrote a simple Go code to prove it.

package main

import "fmt"

func main() {
    var length uint16 = 1024

    var x []int

    for i := 0; i < int(length); i   {
        x = append(x, i)
        fmt.Printf("\nLength is %d. Capacity is %d", len(x), cap(x))
    }
}

From 0 to len(x)==512 it is proven to be true that Go runtime doubles the capacity (a.k.a size). But here the interesting part for me starts: when the len(x) >= 512 I was expecting capacity to be 1024 as 512*2 = 1024. However the result is below:

Length is 513. Capacity is 848 So it is roughly 65 % increase. Can someone explain this to me ?

CodePudding user response:

as of Go 1.14

Go 1.20 has just been released (released 2023-02-01). Work has started on Go 1.21. Read the Go source code to see the changes since Go 1.14 (released 2020-02-25).

For example,

go/src/runtime/slice.go:

// Transition from growing 2x for small slices
// to growing 1.25x for large slices. This formula
// gives a smooth-ish transition between the two.

runtime: make slice growth formula a bit smoother (Committed Mon Sep 27 20:53:51 2021):

Instead of growing 2x for < 1024 elements and 1.25x for >= 1024 elements,
use a somewhat smoother formula for the growth factor. Start reducing
the growth factor after 256 elements, but slowly.

starting cap    growth factor
256             2.0
512             1.63
1024            1.44
2048            1.35
4096            1.30

(Note that the real growth factor, both before and now, is somewhat
larger because we round up to the next size class.)
  • Related