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.select
vs hash.select!
?
你可以随时做一些基准测试:
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)