Skip to content

Instantly share code, notes, and snippets.

@justincampbell
Last active August 29, 2015 13:56
Show Gist options
  • Save justincampbell/9052066 to your computer and use it in GitHub Desktop.
Save justincampbell/9052066 to your computer and use it in GitHub Desktop.
require 'benchmark'
require 'active_support/core_ext'
class Transaction
attr_reader :amount
def initialize(amount)
@amount = amount
end
end
@transactions = (1..1_000_000).map { |n| Transaction.new(n) }
puts RUBY_DESCRIPTION
Benchmark.bm(30) do |benchmark|
benchmark.report("inject with object, +=") do
@transactions.inject(0) { |total, transaction|
total += transaction.amount
}
end
benchmark.report("inject with object, +") do
@transactions.inject(0) { |total, transaction|
total + transaction.amount
}
end
benchmark.report("map and sum") do
@transactions.map(&:amount).sum
end
benchmark.report("map and reduce with symbol") do
@transactions.map(&:amount).reduce(:+)
end
benchmark.report("map and reduce with proc") do
@transactions.map(&:amount).reduce(&:+)
end
if @transactions.respond_to?(:lazy)
benchmark.report("lazy map and reduce") do
@transactions.lazy.map(&:amount).reduce(:+)
end
benchmark.report("lazy map and reduce with proc") do
@transactions.lazy.map(&:amount).reduce(&:+)
end
end
end
$ ruby bench.rb
ruby 2.1.0p0 (2013-12-25 revision 44422) [x86_64-darwin13.0]
user system total real
inject with object, += 0.110000 0.000000 0.110000 ( 0.114151)
inject with object, + 0.110000 0.000000 0.110000 ( 0.100532)
map and sum 0.160000 0.010000 0.170000 ( 0.164063)
map and reduce with symbol 0.170000 0.000000 0.170000 ( 0.183164)
map and reduce with proc 0.190000 0.000000 0.190000 ( 0.187234)
lazy map and reduce 0.410000 0.020000 0.430000 ( 0.423945)
lazy map and reduce with proc 0.390000 0.000000 0.390000 ( 0.387475)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment