Created
January 21, 2016 08:20
-
-
Save pacso/f7e997593bd15bd121d1 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/ips' | |
def products | |
[ | |
{"dt" => "2016-01-01", | |
"quantity" => 122, | |
"amount" => 123000 | |
}, | |
{"dt" => "2016-01-02", | |
"quantity" => 97, | |
"amount" => 97800 | |
}, | |
{"dt" => "2016-01-03", | |
"quantity" => 142, | |
"amount" => 163000 | |
} | |
] | |
end | |
def array_each | |
rowqty = 0 | |
rowamount = 0 | |
products.each do |row| | |
rowqty += row['quantity'] | |
rowamount += row['amount'] | |
row['total_quantity'] = rowqty | |
row['total_amount'] = rowamount | |
end | |
end | |
def array_inject | |
products.inject([0, 0]) do |data, product| | |
data[0] += product['quantity'] | |
data[1] += product['amount'] | |
product['total_quantity'] = data[0] | |
product['total_amount'] = data[1] | |
data | |
end | |
end | |
Benchmark.ips do |x| | |
x.report('Using Array#each') do | |
array_each | |
end | |
x.report('Using Array#inject') do | |
array_inject | |
end | |
x.compare! | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment