Confused about heap usage for empty slices

203 views
Skip to first unread message

mathew murphy

unread,
Sep 7, 2022, 3:01:28 PM9/7/22
to golang-nuts
Running this:

emptyslice := []string{}
sh := (*reflect.SliceHeader)(unsafe.Pointer(&emptyslice))
fmt.Printf("empty slice cap = %d\n", sh.Cap)
fmt.Printf("empty slice len = %d\n", sh.Len)
fmt.Printf("empty slice uintptr = %v\n", sh.Data)

Output:

empty slice cap     = 0
empty slice len     = 0
empty slice uintptr = 824634224152


The non-zero uintptr suggests that something is allocated on the heap. But the cap is 0, so any backing array should have a size of 0. So what is allocated on the heap? Surely not an array of size 0?


mathew

Keith Randall

unread,
Sep 7, 2022, 7:53:12 PM9/7/22
to golang-nuts
That address is not in the heap. It is the address of a special word in the runtime, called runtime.zerobase, which is explicitly for this purpose. It is a place to point things that need to be non-nil but have no size.

Keith Randall

unread,
Sep 7, 2022, 7:56:33 PM9/7/22
to golang-nuts
(Actually, that address is an address on the stack, but that's only because the backing store for emptySlice does not escape. It should also take ~no space.)

Mathew Murphy

unread,
Sep 8, 2022, 10:15:12 AM9/8/22
to golang-nuts
Thanks. So basically, there's no memory benefit or performance benefit to using nil slices over empty slices -- it's ultimately just a matter of how you want them to serialize JSON or get written to databases?


mathew

Axel Wagner

unread,
Sep 8, 2022, 10:17:52 AM9/8/22
to Mathew Murphy, golang-nuts
There is a theoretical (but literally negligible in practice) difference in that the compiler has to write the pointer into the slice. But yes, realistically, there is no difference.

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/ab489f02-e391-41cd-93ef-e415661a886bn%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages