哪个是在Golang中初始化地图的更好方法?

iwa*_*wat 65 go

作为map参考类型.有什么区别:?

m := make(map[string]int32)
Run Code Online (Sandbox Code Playgroud)

m := map[string]int32{}
Run Code Online (Sandbox Code Playgroud)

Lin*_*ope 103

一个允许您初始化容量,一个允许您初始化值:

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

VS

// Initializes a map with an entry relating the name "bob" to the number 5
m := map[string]int{"bob": 5} 
Run Code Online (Sandbox Code Playgroud)

对于容量为0的空地图,它们是相同的,只是偏好.

  • 注意,第一个指定*初始分配*; 它仍然可以超出指定的大小,具有与不使用大小相同的性能.好处是添加到地图的前15个(在此示例中)项目不需要任何地图大小调整.我之所以提到这一点,是因为我看到有人提到地图`make`并说这意味着"制作一张最多15件物品的地图",而应该将其解释为"一张有至少15件物品的地图"或"一张约有15个项目的地图". (20认同)
  • 我尝试对这两种情况进行计时,看起来地图文字在所有情况下都更快。示例代码是 https://repl.it/repls/CriticalRepentantAstrangiacoral 。对此有什么想法吗? (2认同)