地图中的最大元素数量

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

Maximum number of elements in map

问题

在Go语言中,Map可以存储的最大元素数量取决于可用的内存。由于Map是基于哈希表实现的,它的大小是动态的,可以根据需要进行扩展。

如果你需要频繁地从Map中访问数据,并且程序运行时间较长,向Map中添加元素并从中检索可能是一个不错的选择。Map提供了快速的查找操作,平均情况下的时间复杂度为O(1)。但是,需要注意的是,Map的性能可能会受到哈希冲突的影响,因此在设计程序时需要考虑到这一点。

另外,如果你需要按照特定的顺序遍历Map中的元素,可以考虑使用其他数据结构,例如Slice或者LinkedHashMap。这些数据结构可以提供更好的顺序性能。

总之,根据你的具体需求和程序的特点,选择合适的数据结构来存储和访问数据是很重要的。

英文:

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?

答案1

得分: 18

在地图中,元素的数量没有理论上的限制,除了地图长度类型的最大值,即intint的最大值取决于您编译到的目标架构,对于32位系统,它可能是1 << 31 - 1 = 2147483647,对于64位系统,它可能是1 << 63 - 1 = 9223372036854775807

请注意,作为实现限制,您可能无法添加完全达到最大整数元素数量,但数量的数量级将是相同的。

由于内置的map类型使用哈希映射实现,访问时间复杂度通常为O(1),因此向地图中添加许多元素是完全可以的,您仍然可以非常快速地访问元素。但请注意,添加许多元素将导致重新哈希和重建内部结构,这将需要一些额外的计算 - 当向地图添加新键时,这可能会偶尔发生。

如果您可以“猜测”或估计地图的大小,您可以创建具有大容量的地图以避免重新哈希。例如,您可以像这样创建一个具有一百万个元素空间的地图:

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

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 &lt;&lt; 31 - 1 = 2147483647 in case of 32 bit, and 1 &lt;&lt; 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)

答案2

得分: 1

“最大数量”?实际上几乎没有。

“一个好主意”?衡量起来,没有一个普遍的答案。

英文:

"A maximum number"? Practically no.

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

huangapple
  • 本文由 发表于 2015年9月16日 13:55:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/32600763.html
匿名

发表评论

匿名网友

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

确定