Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@srt32
Created April 14, 2014 22:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save srt32/10687302 to your computer and use it in GitHub Desktop.
Save srt32/10687302 to your computer and use it in GitHub Desktop.
benchmarks for map/inject vs SQL sum. See the sample app here: https://github.com/srt32/benchmarks_example
desc 'Benchmark funds_raised methods'
ITERATIONS = 1000
task benchmark_sql: :environment do
campaign = Campaign.last
Benchmark.bm do |bm|
bm.report('sql') do
ITERATIONS.times do
Campaign.uncached do
campaign.funds_raised_sql
campaign.reload
end
end
end
end
end
task benchmark_ruby: :environment do
campaign = Campaign.last
Benchmark.bm do |bm|
bm.report('ruby') do
ITERATIONS.times do
Campaign.uncached do
campaign.funds_raised_ruby
campaign.reload
end
end
end
end
end
## Sample results for 1000 iterations
#
# user system total real
# ruby 17.660000 1.330000 18.990000 ( 20.545473)
# sql 0.690000 0.070000 0.760000 ( 1.045379)
class Campaign < ActiveRecord::Base
has_many :loans
def funds_raised_sql
loans.sum(:amount)
end
def funds_raised_ruby
loans.map(&:amount).inject(:+)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment