使用/不使用make创建地图

huangapple go评论72阅读模式
英文:

Creating map with/without make

问题

var m = map[string]int{} 和 var m = make(map[string]int) 之间到底有什么区别?第一个只是更快地初始化字段的快捷方式吗?是否有性能方面的考虑?

英文:

What exactly is the difference between

var m = map[string]int{}

and

var m = make(map[string]int)

Is the first just a shortcut for faster field initialization? Are there performance considerations?

答案1

得分: 61

第二种形式总是创建一个空的映射。

第一种形式是映射字面量的一种特殊情况。映射字面量允许创建_非空_映射:

m := map[bool]string{false: "FALSE", true: "TRUE"}

现在是你的(广义的)示例:

m := map[T]U{}

是一个没有初始值(键/值对)的映射字面量。它与下面的代码完全等价:

m := make(map[T]U)

此外,make 是指定映射初始容量大于初始分配元素数量的唯一方式。例如:

m := make(map[T]U, 50)

将创建一个具有足够空间来容纳50个元素的映射。如果你知道映射将会增长,这样做可以减少未来的分配次数,这可能是有用的。

英文:

The second form always creates an empty map.

The first form is a special case of a map literal. Map literals allow to create non empty maps:

m := map[bool]string{false: "FALSE", true: "TRUE"}

Now your (generalized) example:

m := map[T]U{}

is a map literal with no initial values (key/value pairs). It's completely equivalent to:

m := make(map[T]U)

Additionally, make is the only way to specify an initial capacity to your map which is larger than the number of elements initially assigned. Example:

m := make(map[T]U, 50)

will create a map with enough space allocated to hold 50 items. This can be useful to reduce future allocations, if you know the map will grow.

huangapple
  • 本文由 发表于 2013年6月6日 18:40:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/16959992.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定