Skip to content

Instantly share code, notes, and snippets.

@jamie
Created March 21, 2014 17:55
Show Gist options
  • Save jamie/9691823 to your computer and use it in GitHub Desktop.
Save jamie/9691823 to your computer and use it in GitHub Desktop.
require 'ostruct'
require 'money'
class Array
def sum
inject{|a,b| a+b }
end
end
TIMES = 1_000
SIZES = [10, 100, 1_000, 10_000]
require 'benchmark'
Benchmark.bmbm do |x|
SIZES.each do |size|
ary = ([1] * size).map{ OpenStruct.new(:balance => Money.new(rand(1000))) }
x.report(".map.sum (#{size})") { TIMES.times { ary.map(&:balance).sum.to_money }}
x.report(".inject (#{size})") { TIMES.times { ary.inject(Money.new(0)){|memo, customer| memo + customer.balance } }}
end
end
Rehearsal ---------------------------------------------------
.map.sum (10) 0.030000 0.000000 0.030000 ( 0.036481)
.inject (10) 0.070000 0.000000 0.070000 ( 0.069186)
.map.sum (100) 0.480000 0.000000 0.480000 ( 0.484167)
.inject (100) 0.490000 0.000000 0.490000 ( 0.494730)
.map.sum (1000) 5.450000 0.010000 5.460000 ( 5.460881)
.inject (1000) 5.380000 0.010000 5.390000 ( 5.393002)
.map.sum (4000) 23.440000 0.030000 23.470000 ( 23.495543)
.inject (4000) 22.270000 0.030000 22.300000 ( 22.324168)
----------------------------------------- total: 57.690000sec
user system total real
.map.sum (10) 0.040000 0.000000 0.040000 ( 0.036330)
.inject (10) 0.040000 0.000000 0.040000 ( 0.038244)
.map.sum (100) 0.470000 0.000000 0.470000 ( 0.466925)
.inject (100) 0.480000 0.000000 0.480000 ( 0.482890)
.map.sum (1000) 5.270000 0.010000 5.280000 ( 5.288732)
.inject (1000) 5.380000 0.010000 5.390000 ( 5.393124)
.map.sum (4000) 23.390000 0.030000 23.420000 ( 23.446630)
.inject (4000) 22.410000 0.030000 22.440000 ( 22.456908)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment