Skip to content

Instantly share code, notes, and snippets.

@rainchen
Last active November 16, 2016 07:01
Show Gist options
  • Save rainchen/6c6bcb3fe4fc22512a36e50adb77049b to your computer and use it in GitHub Desktop.
Save rainchen/6c6bcb3fe4fc22512a36e50adb77049b to your computer and use it in GitHub Desktop.
benchmark for active_record_vs_exception
# ref: http://blog.arkency.com/2016/11/ruby-exceptions-are-4400-times-faster-than-activerecord-base-number-create/
require 'active_record'
require 'benchmark/ips'
ActiveRecord::Base.logger = nil
ActiveRecord::Base.establish_connection adapter: 'sqlite3',
database: ':memory:'
ActiveRecord::Schema.define do
create_table :whatevers do |table|
table.column :text, :string
end
end
Whatever = Class.new(ActiveRecord::Base)
Benchmark.ips do |bench|
bench.report('new record') { Whatever.new(text: 'meh') }
bench.report('SQL query: write') { Whatever.create(text: 'meh') }
bench.report('SQL query: read') { Whatever.find(1) }
bench.report('exception hit') { raise StandardError.new rescue nil }
bench.report('exception miss') { raise StandardError.new if false }
bench.compare!
end
@rainchen
Copy link
Author

benchmark result:

-- create_table(:whatevers)
   -> 0.0103s
Warming up --------------------------------------
          new record     2.588k i/100ms
    SQL query: write   203.000  i/100ms
     SQL query: read   918.000  i/100ms
       exception hit    44.831k i/100ms
      exception miss   206.275k i/100ms
Calculating -------------------------------------
          new record     27.514k (±11.3%) i/s -    137.164k in   5.061244s
    SQL query: write      2.107k (± 7.5%) i/s -     10.556k in   5.039481s
     SQL query: read      7.884k (±17.0%) i/s -     38.556k in   5.048059s
       exception hit    534.798k (±12.5%) i/s -      2.645M in   5.040984s
      exception miss      8.070M (±22.1%) i/s -     37.955M in   5.015018s

Comparison:
      exception miss:  8069995.6 i/s
       exception hit:   534798.4 i/s - 15.09x  slower
          new record:    27514.4 i/s - 293.30x  slower
     SQL query: read:     7884.2 i/s - 1023.56x  slower
    SQL query: write:     2107.1 i/s - 3829.83x  slower

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