Skip to content

Instantly share code, notes, and snippets.

@lucianosousa
Last active January 15, 2016 01:09
Show Gist options
  • Save lucianosousa/642e182eec4f6da356cb to your computer and use it in GitHub Desktop.
Save lucianosousa/642e182eec4f6da356cb to your computer and use it in GitHub Desktop.
Second benchmark for AR queries
require 'active_support'
require 'active_record'
require 'benchmark/ips'
ActiveRecord::Base.establish_connection adapter: 'sqlite3', database: ':memory:'
ActiveRecord::Base.connection.instance_eval do
create_table(:customers) { |c| c.string :name }
end
class Customer < ActiveRecord::Base; end
name = 'Luciano Sousa'
Customer.create! name: name
Benchmark.ips do |x|
x.report('where_first') { Customer.where(name: name).first }
x.report('find_by_name') { Customer.find_by_name(name) }
x.report('find_by') { Customer.find_by(name: name) }
x.compare!
end
@lucianosousa
Copy link
Author

$ ruby benchmark2.rb
Calculating -------------------------------------
where_first      332.000  i/100ms
find_by_name 922.000  i/100ms
find_by            930.000  i/100ms
-------------------------------------------------
where_first      3.416k (±10.2%) i/s -     16.932k
find_by_name 9.194k (± 8.0%)  i/s -     46.100k
find_by            9.345k (±10.7%) i/s -     46.500k

Comparison:
find_by:             9345.0 i/s
find_by_name:  9193.6 i/s - 1.02x slower
where_first:       3415.8 i/s - 2.74x slower

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