Senior
Kuidas optimaalselt luua kaarti, kui teada, et sisendloend sisaldab miljonit elementi?
sobes.tech AI
Vastus AI-lt
To optimally create a map in Go, if the size of the input slice (for example, one million elements) is known in advance, it is recommended to immediately allocate the necessary capacity using the make function, specifying capacity. This will prevent multiple memory reallocations and improve performance.
Example:
input := make([]string, 1000000) // example input slice
// Initialize map with pre-defined capacity
m := make(map[string]int, len(input))
for _, v := range input {
m[v]++
}
This way, the map is created with the appropriate size, optimizing work with a large number of elements.