DEV Community


Discussion on: Golang Garbage Collector 101

dev117uday profile image
Uday Yadav Author

Thank you for the feedback

i looked into the Go's length and capacity concept. Yes when you use make to allocate, and print the len and cap of slice, they are same but still compiler allocates some more memory on heap. I dont exactly remember where i learned about this, but there is something called backing array in go which is basically some extra memory allocated for slice to expand. Running GODEBUG=gctrace=1 always shows more memory being allocated than specified

In the article saying the length and capacity is not same is definitely wrong (i will edit this soon). I will to look into this more and try to provide a better explaination

Also in my markdown editor, i did specify and language for code block but somehow didn't get copied from there, will edit that too

Thanks again

davidkroell profile image
David Kröll

Hi again,

I've done some additional research about the concepts and paradigm of the slice data type. Basically there are the three fields len, cap and data (the backing array you mentioned). As you already pointed out, there is more memory allocated than the cap and len (which are the same when using make) state.

These two values len and cap have to be stored also, in order to not access memory outside the bounds of the backing array. There is probably some memory usage hidden in these fields (as far as my understanding goes, this will only take two words of memory).

So where does the additional memory come from?
I believe this is to some extend based on the Go runtime. There is some space needed for the stack, Goroutine handling, the GC bookkeeping, and possibly many more.

Thread Thread
dev117uday profile image
Uday Yadav Author

I think its really good explaination of what's happening underneath. When i ran the program with s := make([]byte, 5000) it still show mem.TotalAlloc in between 80000 - 120000

finding resoure & explaination about this is bit hard, thanks you giving your time and sharing knowledge

i will update the article soon ( i have my uni exams coming up )