Skip to content

Instantly share code, notes, and snippets.

@janko
Last active September 11, 2020 21:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save janko/688fcf44aa5f47a2671a4f5281546c72 to your computer and use it in GitHub Desktop.
Save janko/688fcf44aa5f47a2671a4f5281546c72 to your computer and use it in GitHub Desktop.
Comparing performance of Sequel and Active Record when fetching 1000 records
require "bundler/inline"
gemfile do
source "https://rubygems.org"
gem "activerecord", "6.0.3.3", require: "active_record"
gem "sequel", "5.36"
gem "sequel_pg", "1.13.0", require: false
gem "pg", "1.2.3"
gem "mysql2", "0.5.3"
gem "benchmark-ips", require: "benchmark/ips"
gem "memory_profiler"
end
CONFIGURATIONS = [
{ adapter: "postgresql", database: "sequel" },
{ adapter: "mysql2", database: "sequel" },
]
Sequel.database_timezone = :utc # makes mysql2 client faster
Sequel::Model.cache_anonymous_models = false
def memory(name, &block)
result = MemoryProfiler.report(&block)
puts "#{name} – #{result.total_allocated} allocated objects"
end
CONFIGURATIONS.each do |configuration|
puts
puts "Database configuration: #{configuration}"
db = Sequel.connect(**configuration, keep_reference: false)
ActiveRecord::Base.establish_connection(**configuration)
db.create_table! :articles do
primary_key :id
String :title
String :body
Boolean :published
Integer :read_count
Integer :comment_count
Integer :position
Time :created_at
Time :updated_at
Time :published_at
end
# insert 1000 dummy records
db[:articles].multi_insert Array.new(1000, {
title: "My title",
body: "My longer descriptive body",
published: true,
read_count: 123948,
comment_count: 123,
created_at: Sequel::CURRENT_TIMESTAMP,
updated_at: Sequel::CURRENT_TIMESTAMP,
published_at: Sequel::CURRENT_TIMESTAMP,
})
activerecord_model = Class.new(ActiveRecord::Base) { self.table_name = :articles }
sequel_model = Sequel::Model(db[:articles])
Benchmark.ips do |x|
x.config(warmup: 5, time: 20)
x.report("activerecord (w/o reading)") { activerecord_model.all.to_a }
x.report("activerecord (w/ reading)") { activerecord_model.all.each(&:attributes) }
x.report("sequel (w/o reading)") { sequel_model.all }
x.report("sequel (w/ reading)") { sequel_model.all.each(&:values) }
x.compare!
end
memory("activerecord (w/o reading)") { activerecord_model.all.to_a }
memory("activerecord (w/ reading)") { activerecord_model.all.each(&:attributes) }
memory("sequel (w/o reading)") { sequel_model.all }
memory("sequel (w/ reading)") { sequel_model.all.each(&:values) }
ensure
ActiveRecord::Base.remove_connection
db.disconnect
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment