170

As map is a reference type. What is difference between:?

m := make(map[string]int32)

and

m := map[string]int32{}
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
iwat
  • 3,591
  • 2
  • 20
  • 24
  • 2
    Even http://stackoverflow.com/questions/16959992/creating-map-with-without-make may be the same question, @Jsor's answer is clearer for the question of why. – iwat Jun 26 '15 at 06:13

1 Answers1

269

One allows you to initialize capacity, one allows you to initialize values:

// Initializes a map with space for 15 items before reallocation
m := make(map[string]int32, 15)

vs

// Initializes a map with an entry relating the name "bob" to the number 5
m := map[string]int{"bob": 5} 

For an empty map with capacity 0, they're the same and it's just preference.

Linear
  • 21,074
  • 4
  • 59
  • 70
  • 52
    Note that the first specifies an *initial allocation*; it can still grow beyond the size specified with the same performance as not using a size. The benefit is that the first 15 (in this example) items added to the map will not require any map resizing. I mention this because I've seen people refer to a map `make` and say it means "make a map with at most 15 items" when instead it should be interpreted as "a map with room for at least 15 items" or "a map with around 15 items". – Dave C Jun 26 '15 at 14:56
  • 2
    I tried to time both the cases and looks like map literal is faster in all the cases. Sample code is https://repl.it/repls/CriticalRepentantAstrangiacoral . Any thoughts on this? – Bharath Ram Jan 03 '18 at 21:47
  • @BharathRam if this is true, it's probably a compiler bug and will change from release to release. Also, have you tried swapping the order you do the two cases in? It's possible some string optimization stuff is happening behind the scenes, since you're using the same strings for both benchmarks. – Linear Jan 08 '18 at 05:38
  • Looks like the result is kind of changing when I try it in the online compiler. However, your point also seems to be correct and it has some effect on the running time. It could be doing some kind of caching under the hood. Thanks. – Bharath Ram Jan 08 '18 at 15:28
  • The benchmark is flawed. Swapping the loop order inverses the results making `make()` faster in most cases. – asido Aug 20 '19 at 06:07
  • Just wonder the capacity of the second form – 赣西狠人 Feb 24 '20 at 04:58
  • @辽北狠人 the same as the number of elements – Linear Feb 24 '20 at 04:59
  • Also note, that in the first initialization, the type of `m` will be a `*map[string]int32` but in the second form, it'll be `map[string]int32` Also, is Dave C = Dave Cheney? – kapad Jul 14 '21 at 10:56