"Hashes enumerate their values in the order that the corresponding keys were inserted."
"Hashes enumerate their values in the order that the corresponding keys were inserted."
来自 http://ruby-doc.org/core-2.4.0/Hash.html#method-i-each 的 ruby 文档:
Hashes enumerate their values in the order that the corresponding keys were inserted.
通常,我希望以随机顺序枚举哈希值(使用任意语言)。
ruby 如何跟踪插入顺序?除了哈希桶之外,它是否在键之间保留一个链表?我想这会非常简单,但我真的很惊讶(以一种好的方式)他们首先做到了。
这个 forum 有您正在寻找的确切答案,并且由 Matz 亲自回答。
Could anybody explain why this feature was added?
Useful for some cases, especially for keyword arguments.
Isn't it going to slow down the operations on the Hash?
No. hash reference operation does not touch order information, only
for iteration. Memory consumption increased a bit.
是的,它有一个链表。这可以在不影响典型散列 table 的典型 O(1) 分摊最坏情况步骤复杂性保证的情况下完成,因为所有使链表昂贵的操作(例如删除元素)都与需要遍历有关列表是为了 找到 一个元素,但在这种特殊情况下, "finding" 部分可以通过使用散列 table 查找来短路。
如果您对 Ruby 实现的内部结构感兴趣,我建议您阅读 Rubinius 源代码;它比 YARV 更简洁易读,另外,它是用 Ruby 编写的,您可能已经熟记这种语言。 Rubinius 的 Hash
class 在 core/hash.rb
. Note that current versions of Rubinius use a Hash Array Mapped Trie (HAMT), which is significantly different from the simple traditional hash table that YARV uses, but that has no bearing on the use of the additional linked list. And if you really want to, you can look at an older version 中实现,它仍然具有传统的散列 table.
来自 http://ruby-doc.org/core-2.4.0/Hash.html#method-i-each 的 ruby 文档:
Hashes enumerate their values in the order that the corresponding keys were inserted.
通常,我希望以随机顺序枚举哈希值(使用任意语言)。
ruby 如何跟踪插入顺序?除了哈希桶之外,它是否在键之间保留一个链表?我想这会非常简单,但我真的很惊讶(以一种好的方式)他们首先做到了。
这个 forum 有您正在寻找的确切答案,并且由 Matz 亲自回答。
Could anybody explain why this feature was added?
Useful for some cases, especially for keyword arguments.
Isn't it going to slow down the operations on the Hash?
No. hash reference operation does not touch order information, only for iteration. Memory consumption increased a bit.
是的,它有一个链表。这可以在不影响典型散列 table 的典型 O(1) 分摊最坏情况步骤复杂性保证的情况下完成,因为所有使链表昂贵的操作(例如删除元素)都与需要遍历有关列表是为了 找到 一个元素,但在这种特殊情况下, "finding" 部分可以通过使用散列 table 查找来短路。
如果您对 Ruby 实现的内部结构感兴趣,我建议您阅读 Rubinius 源代码;它比 YARV 更简洁易读,另外,它是用 Ruby 编写的,您可能已经熟记这种语言。 Rubinius 的 Hash
class 在 core/hash.rb
. Note that current versions of Rubinius use a Hash Array Mapped Trie (HAMT), which is significantly different from the simple traditional hash table that YARV uses, but that has no bearing on the use of the additional linked list. And if you really want to, you can look at an older version 中实现,它仍然具有传统的散列 table.