Slice append - what is the actual resize factor?


(Les Way) #1

I have started with a slice []int, of capacity 0 , then I append one integer to it, and whenever it get a resize I print the old capacity, new capacity, and the resize factor. Please look below:
0 1 1 + 0%
1 2 200.000 %
2 4 200.000 %
4 8 200.000 %
8 16 200.000 %
16 32 200.000 %
32 64 200.000 %
64 128 200.000 %
128 256 200.000 %
256 512 200.000 %
512 1024 200.000 %
1024 1280 125.000 %
1280 1696 132.500 %
1696 2304 135.849 %
2304 3072 133.333 %
3072 4096 133.333 %
4096 5120 125.000 %
5120 7168 140.000 %
7168 9216 128.571 %
9216 12288 133.333 %
12288 15360 125.000 %
15360 19456 126.667 %
19456 24576 126.316 %
24576 30720 125.000 %
30720 38912 126.667 %
38912 49152 126.316 %
49152 61440 125.000 %
61440 76800 125.000 %
76800 96256 125.333 %
96256 120832 125.532 %
120832 151552 125.424 %
151552 189440 125.000 %
189440 237568 125.405 %
237568 296960 125.000 %
296960 371712 125.172 %
371712 464896 125.069 %
464896 581632 125.110 %
581632 727040 125.000 %
727040 909312 125.070 %
909312 1136640 125.000 %
1136640 1421312 125.045 %
1421312 1776640 125.000 %
1776640 2221056 125.014 %
2221056 2777088 125.035 %
2777088 3471360 125.000 %
3471360 4339712 125.015 %
4339712 5425152 125.012 %
5425152 6781952 125.009 %
6781952 8477696 125.004 %
8477696 10597376 125.003 %
10597376 13247488 125.007 %
13247488 16560128 125.006 %
16560128 20700160 125.000 %
20700160 25875456 125.001 %
25875456 32345088 125.003 %
32345088 40431616 125.001 %
40431616 50539520 125.000 %
50539520 63174656 125.001 %
63174656 78968832 125.001 %
78968832 98711552 125.001 %
98711552 123389952 125.001 %

What is the formula, how does it decide the new capacity ?


(Norbert Melzer) #2

As this is not specified in the language specification you have to assume that it is an implementation detail of your runtime used.


(Luis) #3

Go to the source :slight_smile:


(Norbert Melzer) #4

Which absolutely proves my point. As it is part of the runtime package and not documented anywhere, not even as a property of the runtime, it should be assumed that growing happens “well enough” and one should not rely on specifics.


(Luis) #5

Yes, I believe is part of Golang philosophy, safe automatic memory management. Also you can assign the size manually if you know the final size. It would run faster instead of resizing the slice each time it’s need it.