Reputation: 11
I know that map is a reference type in Go (it has a pointer to the map entries memory region in its underlying struct). However, I would like to know what is the size of the underlying struct of the map because I want to know if using a pointer to a map as a function argument would be faster than not using a pointer.
Looking at this blog post it seems that the maptype struct has a lot of fields and that it would take a long time to copy (relative to a pointer).
Looking through the golang standard libraries I have found almost no use of *map[x]x so I guess using just map[x]x should be efficient as a function argument. So this leads me to think that maybe the compiler actually replaces map[x]x by a pointer to the maptype struct. Is that the case? If not what actually is happening that may avoid the copying of the maptype struct with its many fields?
Upvotes: 0
Views: 938
Reputation: 166569
The zero value for a Go map
variable is a nil
pointer.
var m map[string]int
make
intializes a map
and sets the map
variable to point to a package runtime
hmap
struct
.
m = make(map[string]int)
In Go, all arguments are passed by value. In the case of a map
value, a reference type, a map
value is a pointer. Therefore, passing a map
value as a function or method argument is fast, you are passing a pointer.
The Go map
runtime
struct
s are currently located in the src/runtime/map.go
Go source file. Since you only see a hmap
pointer, their size is unlikely to be relevant.
See GopherCon 2016: Keith Randall - Inside the Map Implementation.
Upvotes: 1