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

dsp*_*099 4 ruby sorting hash performance

hash = { 'mark' => 1, 'jane' => 1, 'peter' => 35 }.select {|k,v| v > 1}
#=> { 'peter' => 35 }
Run Code Online (Sandbox Code Playgroud)

如果我有数百万个密钥怎么办 - 两者之间有什么区别

hash = hash.selectvs hash.select!

Ven*_*Ven 7

select! 会表现得更好(我会展示MRI的来源,但对其他人来说应该是相同的).

这样做的原因是select需要创建一个全新的Hash对象,并且对于散列中的每个条目,将复制该条目 - 如果该块成功.

在另一方面,select!将,每个键,删除值 - 如果块没有成功 - 就地(而无需创建新对象).


lcg*_*ida 6

你可以随时做一些基准测试:

require 'benchmark'

# Creates a big hash in the format: { 1 => 1, 2 => 2 ... }
big_hash = 100_000.times.inject({}) { |hash, i| hash.tap { |h| h[i] = i }   }
Benchmark.bm do |bm|
   bm.report('select') { big_hash.select{ |k,v| v > 50 } }
   bm.report('select!') { big_hash.select!{ |k,v| v > 50 } }
end

         user       system     total     real
select   0.080000   0.000000   0.080000  (  0.088048)
select!  0.020000   0.000000   0.020000  (  0.021324)
Run Code Online (Sandbox Code Playgroud)