Slice capacity size

hello,
Could you please explain, why this, after the fifth iteration expands the capacity instead of 10 to 12 from 5?
here is the code:

package main

import (
	"fmt"
)

func main() {
	var mySlice = make([]int, 0, 5)

	for i := 0; i < 50; i++ {
		mySlice = append(mySlice, i)
		fmt.Println("Len:", len(mySlice), "Cap:", cap(mySlice), "Val:", mySlice[i])
	}

}

and the playground link:
https://play.golang.org/p/7CHYVN5kgB
thanks a lot

Why do you expect it to be 10?

2 Likes

Try different values for the capacity, e.g., 4, 5, 6, 7, 8 etc. Can you see a pattern?

1 Like

@lutzhorn somewhere I read that it grows by doubling the existing capacity

@christophberger damn, now I see that, I just don’t understand why
3 -> 8
4 -> 8
5 -> 12
6 -> 12
7 -> 16
8 -> 16

Note that all of this is an implementation detail. The runtime does something based, presumably, on statistics and experience to provide good performance without wasting too much memory. The exact sizes are not defined in any spec and can vary from release to release. All in all, it’s not something that should matter…

3 Likes

cool, thank you

As @calmh pointed out, it is an implementation detail that should not bother you when writing Go code. The more important aspect about append is the unexpected effect it can have when two slices point to the same region of the underlying array. Updating the element of one slice also changes the other slice, but when one of the two slices expands beyond capacity, it allocates a new array and the two slices do not influence each other anymore.

2 Likes

The short answer is slices grow by doubling.

The slightly longer answer is sometimes, for small slices, they grow by mor than double. The reason for this is something called a size clas, which is a technique used inside the runtime to avoid fragmentation with small allocations. As sizes get larger, the more they deviate from a powers of two scheme.

Once the size of a slice passes about 1k, it will grow by 1.25x

3 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.