Skip to content

Instantly share code, notes, and snippets.

@yarysh
Created November 20, 2023 17:44
Show Gist options
  • Select an option

  • Save yarysh/2669426e755e2d83059438aa08d8e19b to your computer and use it in GitHub Desktop.

Select an option

Save yarysh/2669426e755e2d83059438aa08d8e19b to your computer and use it in GitHub Desktop.
How do slices grow in Go
package main
import "fmt"
func main() {
initLen, insertions := 64, 1024*10
s := make([]int, 0, initLen)
currCap := cap(s)
for i := 0; i < insertions; i++ {
s = append(s, i)
if currCap < cap(s) {
fmt.Printf(
"Capacity was increased from %d to %d (%.2f%%)\n",
currCap, cap(s), (1-float64(currCap)/float64(cap(s)))*100,
)
currCap = cap(s)
}
}
}
@yarysh
Copy link
Author

yarysh commented Nov 20, 2023

go run main.go

Capacity was increased from 64 to 128 (50.00%)
Capacity was increased from 128 to 256 (50.00%)
Capacity was increased from 256 to 512 (50.00%)
Capacity was increased from 512 to 848 (39.62%)
Capacity was increased from 848 to 1280 (33.75%)
Capacity was increased from 1280 to 1792 (28.57%)
Capacity was increased from 1792 to 2560 (30.00%)
Capacity was increased from 2560 to 3408 (24.88%)
Capacity was increased from 3408 to 5120 (33.44%)
Capacity was increased from 5120 to 7168 (28.57%)
Capacity was increased from 7168 to 9216 (22.22%)
Capacity was increased from 9216 to 12288 (25.00%)

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