Skip to content

Instantly share code, notes, and snippets.

@SamSaffron
Created September 10, 2013 06:45
Show Gist options
  • Save SamSaffron/6505777 to your computer and use it in GitHub Desktop.
Save SamSaffron/6505777 to your computer and use it in GitHub Desktop.
require 'benchmark'
require 'active_support'
@col_map = (1..30).map{|i| ["a#{i}", "b#{i}"]}
@row = Hash[(1..30).map{|i| ["b#{i}", i]}]
def orig(row)
Hash[@col_map.map{|cn, an| [cn, row[an]]}]
end
def naive(row)
hash = {}
index = 0
while index < @col_map.length do
cn,an = @col_map[index]
hash[cn] = row[an]
index += 1
end
hash
end
def each_with_object(row)
@col_map.each_with_object({}) do |(cn, an), hash|
hash[cn]= row[an]
end
end
Benchmark.bmbm do |x|
x.report("original") do
10000.times{ orig(@row) }
end
x.report("naive") do
10000.times{ naive(@row) }
end
x.report("each_with_object") do
10000.times{ each_with_object(@row)}
end
end
@SamSaffron
Copy link
Author

Rehearsal ----------------------------------------------------
original           0.080000   0.010000   0.090000 (  0.091959)
naive              0.080000   0.010000   0.090000 (  0.082822)
each_with_object   0.090000   0.000000   0.090000 (  0.093846)
------------------------------------------- total: 0.270000sec

                       user     system      total        real
original           0.090000   0.000000   0.090000 (  0.087676)
naive              0.080000   0.000000   0.080000 (  0.077203)
each_with_object   0.090000   0.000000   0.090000 (  0.087767)

@baroquebobcat
Copy link

Neat. It's always nice to see some stats. I also played with checking heap usage in addition to time, and got results like this:

original: 1516
naive: 758
each_with_object: 783

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment