Go的Map迭代在官方blog中有提到:
When iterating over a map with a range loop, the iteration order is not specified and is not guaranteed to be the same from one iteration to the next. If you require a stable iteration order you must maintain a separate data structure that specifies that order.
一开始我以为“不保证相同迭代顺序”是指随机迭代,然而在实测中发现,在一个含有2个元素的map中,某个特定元素被访问到的概率远大于其他元素。
在这篇blog中找到了解答,https://blog.twofei.com/847/。
Go的map是哈希表实现,用桶来存储元素,每个桶存储8个元素。
而迭代则是
它是使用快速随机算法随机选了一个桶作为起始桶,并且又快速随机地选择了桶内的任意一个偏移的元素作为起始元素。在迭代的时候,如果桶内
offset + i
处的元素是空的话,就会continue
跳到下一个元素
也就是说,共有n个且不足8个元素时,第一个元素的概率将是(8-n+1)/8而不是1/n。
总的来说就是,is not guaranteed不等于is guaranteed not,不保证相同顺序不等于保证不同顺序,【所有元素数不足8的整数倍的情况下】某一个元素被选中的概率远大于其他元素。