Skip to content

Instantly share code, notes, and snippets.

@dbenhur
Created October 22, 2012 02:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dbenhur/3929357 to your computer and use it in GitHub Desktop.
Save dbenhur/3929357 to your computer and use it in GitHub Desktop.
SO #13002594 Handling array of hashes
#!/usr/bin/env ruby
# Benchmark answers to http://stackoverflow.com/questions/13002594/handling-array-of-hashes
require 'benchmark'
A = [{"lib1"=>"30"}, {"lib2"=>"30"}, {"lib9"=>"31"}, {"lib2"=>"31"}, {"lib3"=>"31"}, {"lib1"=>"32"}, {"l\
ib2"=>"32"}, {"lib1"=>"33"}, {"lib3"=>"36"}, {"lib2"=>"36"}, {"lib1"=>"37"}]
def to_a_flat
A.map(&:to_a).flatten(1).each_with_object({}) do |(k, v), h|
h[k] ||= []
h[k] << v.to_i
end
end
def to_a_flat_construct
Hash[A.map(&:to_a).flatten(1).group_by(&:first).map { |k, v| [k, v.map(&:last).map(&:to_i)] }]
end
def group_by_each
result = {}
A.group_by { |x| x.keys.first }.each_pair do |k, v|
result[k] = v.map { |e| e.values.first.to_i }
end
end
def group_by_each_construct
Hash[A.group_by { |x| x.keys[0] }.map { |k, v| [k, v.map { |e| e.values[0].to_i }]}]
end
def nested_iter
A.each_with_object({}) {|e,r| e.each {|k,v| (r[k] ||= []) << v.to_i } }
end
cases = %w{to_a_flat to_a_flat_construct group_by_each group_by_each_construct nested_iter}
N = 250_000
puts RUBY_DESCRIPTION
Benchmark.bmbm(25) do |x|
cases.each do |the_case|
x.report(the_case) { N.times { send the_case } }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment