Last active
September 16, 2018 11:30
-
-
Save landovsky/6a1b29cbf13d0cf81bad12b6ba472416 to your computer and use it in GitHub Desktop.
Iterate v. reduce over array of hashes
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
module Test | |
def self.iterate(array) | |
Hash.new(0).tap do |result| | |
array.each do |hash| | |
hash.each do |key, val| | |
result[key] = result[key] + val | |
end | |
end | |
end | |
end | |
def self.reduce(array) | |
array.reduce do |memo, hash| | |
memo.merge(hash) do |_key, old_val, new_val| | |
old_val + new_val | |
end | |
end | |
end | |
def self.random_array_of_hashes(array_size) | |
Array.new(array_size) { { a: rand(1000), b: rand(1000) } } | |
end | |
def self.bench(ntimes = 1000, array_size = 1000) | |
arr = random_array_of_hashes(array_size) | |
Benchmark.bmbm do |results| | |
results.report('reduce: ') do | |
ntimes.times { reduce(arr) } | |
end | |
results.report('iterate: ') do | |
ntimes.times { iterate(arr) } | |
end | |
end | |
end | |
end | |
Test.bench |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment