[go-nuts] Re: map[X]Y or map[X]*Y ?
In addition to the god points that others have made, there is a difference in the way that memory will be allocated. See https://play.golang.org/p/l6d4lODiDx and pay attention to the "delta" lines. In this particular example, using a map to a pointer does a Malloc for every map item, whereas using a map to value does not. For 10,000 items: pointer delta : Alloc: 401248, TotalAlloc: 401248, Mallocs: 10543 value delta : Alloc: 369512, TotalAlloc: 369512, Mallocs: 623 Of course, other uses could behave differently. On Friday, May 12, 2017 at 8:00:00 AM UTC-4, aktungmak wrote: > > Setting aside the receiver types of methods for the moment, if we consider > the following declaration: > > type Y struct { > //some fields > } > > Which of the following would be "better" (from a speed and storage usage > viewpoint)? > > map[X]Y > map[X]*Y > > If we consider that this map could be handed between different functions. > Does it make any difference to use a pointer? Or does it make no > difference, since the map is already a reference type and functions are > receiving a copy of the pointer to the map and not a copy of the map value? > > Thanks! > -- 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+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.
[go-nuts] Re: map[X]Y or map[X]*Y ?
> > type Y struct { > //some fields > } > > This rather depends on what those some fields ARE, and whether type Y is conceptually mutable or immutable. For example, I might make a lightweight struct just to group a pair of values; X/Y coordinates, or Latitude and Longitude: type LatLon struct { Latitude, Longitude float64 } or the like, and in that case, I might treat it as immutable, and just make a new one if I needed changes, in which case doing a map[string]LatLon would be fine. If the struct is larger or is mutable, then a pointer makes more sense. BUT! There is one *critical* case to consider. type Something struct { guard sync.Mutex ... guarded things } This one MUST be done as a pointer, otherwise you are copying the mutex when you assign to the map, or assign from the map to a variable. As the docs say, "A Mutex must not be copied after first use." So if you have mutexes or mutable values in the struct, best to use *. "Only use the non-pointer map when your structs are simple, small, and immutable" is probably a reasonable rule of thumb. -- 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+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.