Does make Matter When Creating Maps?
When creating maps in Go, developers have two options:
var m = map[string]int{}
var m = make(map[string]int)
While the former may seem like a shortcut for faster field initialization, both options have subtle differences.
Map Literals vs. make
The first form is a special case of a map literal, which allows the creation of non-empty maps with specific key-value pairs. For instance:
m := map[bool]string{false: "FALSE", true: "TRUE"}
In contrast, the second form using make always creates an empty map. It's equivalent to the map literal with no initial values, such as:
m := map[string]int{}
Initial Capacity
The key distinction between the two approaches lies in the ability to specify an initial capacity. make allows you to allocate space for a specific number of items, even if they're not initially assigned. This can help reduce future allocations if you anticipate the map growing significantly. For example:
m := make(map[string]int, 50)
This creates a map with enough space for 50 items, potentially reducing allocations as the map expands.
Best Practice
In general, the choice between the two methods depends on the situation. If you're creating an empty map where performance is not critical, either option will suffice. However, if you anticipate a large map or want to set the initial capacity, using make is recommended.
The above is the detailed content of Does `map` or `make` Matter When Creating Maps in Go?. For more information, please follow other related articles on the PHP Chinese website!