Created
September 10, 2013 06:45
-
-
Save SamSaffron/6505777 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Author
SamSaffron
commented
Sep 10, 2013
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