Sunil
Sunil

Reputation: 581

Maximum number of elements in map

What is the maximum number of elements that can be stored in a Map in GO? If I need to access data from Map frequently, is it a good idea to keep on adding items to Map and retrieving from it, in a long running program?

Upvotes: 3

Views: 12510

Answers (2)

icza
icza

Reputation: 417662

There is no theoretical limit to the number of elements in a map except the maximum value of the map-length type which is int. The max value of int depends on the target architecture you compile to, it may be 1 << 31 - 1 = 2147483647 in case of 32 bit, and 1 << 63 - 1 = 9223372036854775807 in case of 64 bit.

Note that as an implementation restriction you may not be able to add exactly max-int elements, but the order of magnitude will be the same.

Since the builtin map type uses a hashmap implementation, access time complexity is usually O(1), so it is perfectly fine to add many elements to a map, you can still access elements very fast. Note that however adding many elements will cause a rehashing and rebuilding the internals, which will require some additional calculations - which may happen occasionally when adding new keys to the map.

If you can "guess" or estimate the size of your map, you can create your map with a big capacity to avoid rehashing. E.g. you can create a map with space for a million elements like this:

m := make(map[string]int, 1e6)

Upvotes: 19

Volker
Volker

Reputation: 42413

"A maximum number"? Practically no.

"A good idea"? Measure, there cannot be a general answer.

Upvotes: 1

Related Questions