Skip to content

Instantly share code, notes, and snippets.

@cameron-martin
Last active August 29, 2015 14:05
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 cameron-martin/b907ec43a9d8b9303bdc to your computer and use it in GitHub Desktop.
Save cameron-martin/b907ec43a9d8b9303bdc to your computer and use it in GitHub Desktop.
require 'benchmark'
require 'ostruct'
n = 10_000
array = Array.new(1000) { |index| OpenStruct.new.tap { |struct| struct.price = index } };
Benchmark.bmbm do |x|
x.report('two stages') { n.times { array.map(&:price).inject(0, :+) } }
x.report('one stage') { n.times { array.inject(0) { |sum, product| sum += product.price } } }
x.report('lazy') { n.times { array.lazy.map(&:price).inject(0, :+) } }
end;
@cameron-martin
Copy link
Author

$ ruby -v
ruby 2.1.2p95 (2014-05-08 revision 45877) [x86_64-darwin13.0]
Rehearsal ----------------------------------------------
two stages   3.110000   0.030000   3.140000 (  3.142049)
one stage    3.340000   0.000000   3.340000 (  3.351796)
lazy         6.290000   0.010000   6.300000 (  6.293662)
------------------------------------ total: 12.780000sec

                 user     system      total        real
two stages   3.150000   0.020000   3.170000 (  3.174854)
one stage    3.300000   0.010000   3.310000 (  3.313886)
lazy         6.230000   0.010000   6.240000 (  6.246250)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment