Skip to content

Instantly share code, notes, and snippets.

@sgrif
Created June 12, 2014 16:07
Show Gist options
  • Save sgrif/f387e960fa0998b13afd to your computer and use it in GitHub Desktop.
Save sgrif/f387e960fa0998b13afd to your computer and use it in GitHub Desktop.
Benchmark used for HABTM performance comparison
require_relative '../load_paths'
require 'active_record'
ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:')
class Book < ActiveRecord::Base
has_and_belongs_to_many :genres
has_many :genre_memberships
has_many :genres2, through: :genre_memberships, source: :genre
end
class Genre < ActiveRecord::Base
has_and_belongs_to_many :books
has_many :genre_memberships
has_many :books2, through: :genre_memberships, source: :book
end
class LibraryEntry < ActiveRecord::Base
belongs_to :book
end
class GenreMembership < ActiveRecord::Base
belongs_to :book
belongs_to :genre
end
ActiveRecord::Schema.define do
create_table :library_entries do |t|
t.integer :book_id
end
create_table :books do |t|
end
create_table :genres do |t|
end
create_table :books_genres, id: false do |t|
t.integer :book_id
t.integer :genre_id
end
create_table :genre_memberships do |t|
t.integer :book_id
t.integer :genre_id
end
end
puts "Initializing database."
books = []
genres = []
library_entries = []
ActiveRecord::Base.transaction do
genres = (1..20).map { Genre.create! }
books = (1..5000).map do
book = Book.new
g = genres.sample(5)
book.genres = g
book.genres2 = g
book.save!
book
end
library_entries = (1..5000).map do |i|
l = LibraryEntry.new
l.book = books[i]
l.save!
l
end
end
puts "Finished initializing database."
require 'benchmark/ips'
Benchmark.ips do |bm|
bm.report('no id') { LibraryEntry.limit(200).includes(book: :genres).to_a }
bm.report('with id') { LibraryEntry.limit(200).includes(book: :genres2).to_a }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment