Report abuse

Managed Open Source blog code


			
# http://blog.managedopensource.com
# http://blog.managedopensource.com/2007/10/31/reversal-of-code-performance-optimizations-from-ruby-1-8-to-1-9

Ruby benchmark code


			
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