I initialized a hash as in this question and ran some benchmarks.
Benchmark.measure { a = h.keys }
#=> 0.010000 0.000000 0.010000 ( 0.019832)
Benchmark.measure { a.each { |k| } }
#=> 0.060000 0.000000 0.060000 ( 0.057262)
Benchmark.measure { h.each { |k, v| } }
#=> 0.320000 0.000000 0.320000 ( 0.319768)
Benchmark.measure { h.each_key { |k| } }
#=> 0.310000 0.000000 0.310000 ( 0.312656)
Benchmark.measure { h.each_pair { |k, v| } }
#=> 0.330000 0.000000 0.330000 ( 0.331452)
I have thought that turning the hash into an array of keys would be slower, but it's not, and each_key
has similar performance to each
. Why is this? What is the best approach?