require 'benchmark'
hash = {}
1_000_000.times {|i| hash["name#{i}"] = "value#{i}" }
def concat(value)
"value is #{value}"
end
Benchmark.bm do |b|
b.report("for ") { for key in hash.keys; concat(hash[key]); end; }
b.report("each") { hash.keys.each {|key| concat(hash[key]) } }
end
Benchmark.bm do |b|
b.report("<< ") do
list = []
for key in hash.keys
list << concat(hash[key])
end
list
end
b.report("collect") do
hash.keys.collect { |key| concat(hash[key]) }
end
end