ruby - 在 Ruby 哈希上调用时, `select` 和 `select!` 之间是否存在性能差异?

标签 ruby performance sorting hash

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/

相关文章:

ruby-on-rails - Hartl Rails 教程第 2 章, "hello world"未显示在 http ://localhost:3000 中

ruby - 如何为 Dry::Validation.Params 方案设置默认值?

c++ - 将内联加速 void a(string b) { cout << b; }

java - 快速查找某个范围包含数字的方法

javascript - 如何对 luxon 对象数组执行排序

javascript - 在数组中查找两个重复值的最佳技术是什么?

ruby - 自动将院子文档框架添加到现有的 Rails 遗留代码中

ruby - 根据在同一工厂的另一个字段中设置的数字创建工厂字段值

Android Instrumentation 测试关注 : debug vs. Release模式

php - 使用 php、ajax 和 jquery 对 mysql 表进行排序