英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论