Skip to content

Instantly share code, notes, and snippets.

@njakobsen
Last active Dec 22, 2015
Embed
What would you like to do?
Test performance of ActiveRecord Includes. This is a test script designed to test for a performance regression when using the .includes() method on a scope.
begin
class CreateModels < ActiveRecord::Migration
def change
create_table :items do |t|
end
create_table :events do |t|
t.belongs_to :item
end
create_table :event_people do |t|
t.belongs_to :event
t.belongs_to :person
end
create_table :people do |t|
end
end
end
class Item < ActiveRecord::Base
has_many :events
has_many :event_people, :through => :events
has_many :people, :through => :events
end
class Event < ActiveRecord::Base
belongs_to :item
has_many :event_people
has_many :people, :through => :event_people
end
class EventPerson < ActiveRecord::Base
belongs_to :event
belongs_to :person
end
class Person < ActiveRecord::Base
end
CreateModels.new.change
puts "Populating Database"
1000.times do
Item.create
end
Item.all.each_with_index do |item|
event = Event.new
event.people.build
event.people.build
item.events << event
end
rescue => e
# Tables already exist
puts e.message
ensure
require 'benchmark'
Benchmark.benchmark("#{Rails.version} - #{ActiveRecord::Base.configurations[Rails.env]['adapter']}\n", 40) do |x|
x.report('limit 100 has_many') { 1.times { Item.preload(:events).limit(100).order(:id).to_a } }
x.report('limit 100 has_many_through') { 1.times { Item.preload(:event_people).limit(100).order(:id).to_a } }
x.report('limit 100 double has_many_through') { 1.times { Item.preload(:people).limit(100).order(:id).to_a } }
x.report('limit 1000 has_many') { 1.times { Item.preload(:events).limit(1000).order(:id).to_a } }
x.report('limit 1000 has_many_through') { 1.times { Item.preload(:event_people).limit(1000).order(:id).to_a } }
x.report('limit 1000 double has_many_through') { 1.times { Item.preload(:people).limit(1000).order(:id).to_a } }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment