hash = { 'mark' => 1, 'jane' => 1, 'peter' => 35 }.select {|k,v| v > 1}
#=> { 'peter' => 35 }
如果我有数百万个 key 怎么办 - 之间有区别吗
hash = hash.select
vs hash.select!
?
最佳答案
select!
会表现得更好(我将显示 MRI 的源代码,但其他的应该相同)。
原因是select
需要 create a whole new Hash
object ,并且会,for each entry in the hash , copy the entry - if the block succeeds .
另一方面,select!
, 将, for each key , remove the value - if the block doesn't succeed - in-place (无需创建新对象)。
关于ruby - 在 Ruby 哈希上调用时, `select` 和 `select!` 之间是否存在性能差异?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39161340/