Skip to content

Instantly share code, notes, and snippets.

@tbuehlmann
Created July 31, 2024 10:05
Show Gist options
  • Save tbuehlmann/b2afa0ffe7c2fe3eeb8acbd56dea5f40 to your computer and use it in GitHub Desktop.
Save tbuehlmann/b2afa0ffe7c2fe3eeb8acbd56dea5f40 to your computer and use it in GitHub Desktop.
require "bundler/inline"
gemfile do
source "https://rubygems.org"
gem "activerecord", "7.1.3.4"
gem "sqlite3"
gem "benchmark-ips"
end
require "active_record"
ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:')
ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Schema.define do
create_table :records do |t|
t.string :attribute_that_must_not_be_blank
t.datetime :created_at, null: false
t.datetime :updated_at, null: false
end
end
class Record < ActiveRecord::Base
validates :attribute_that_must_not_be_blank, presence: true
end
# warmup AR
Record.create(attribute_that_must_not_be_blank: "foo")
Benchmark.ips do |x|
x.report("exception") do
record = Record.new
begin
record.save!
# if
rescue ActiveRecord::RecordInvalid
# else
end
end
x.report("if else") do
record = Record.new
if record.save
# if
else
# else
end
end
x.compare!
end
# Warming up --------------------------------------
# exception 787.000 i/100ms
# if else 3.329k i/100ms
# Calculating -------------------------------------
# exception 7.774k (± 3.1%) i/s - 39.350k in 5.067153s
# if else 33.353k (± 3.4%) i/s - 169.779k in 5.096774s
# Comparison:
# if else: 33352.6 i/s
# exception: 7773.6 i/s - 4.29x slower
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment