Skip to content

Instantly share code, notes, and snippets.

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 yuroyoro/16df3fa6458c1c768c1e to your computer and use it in GitHub Desktop.
Save yuroyoro/16df3fa6458c1c768c1e to your computer and use it in GitHub Desktop.
require 'benchmark/ips'
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
ActiveRecord::Migration.verbose = false
CreateModels.new.change
rescue => e
# Tables already exist
# puts e.message
end
unless Item.count >= 100
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
end
puts "=" * 80
puts "Benchmark : Instantiate ActiveRecord::Associations::CollectionProxy"
puts "#{Rails.version} - #{ActiveRecord::Base.configurations[Rails.env]['adapter']}"
puts "=" * 80
puts ""
rails3 = (Rails.version.split(".").first.to_i < 4)
items = Item.all.to_a
Benchmark.ips do |x|
x.report('has_many') {
items.each do |item|
association = item.association(:events)
if rails3
ActiveRecord::Associations::CollectionProxy.new(association)
else
ActiveRecord::Associations::CollectionProxy.new(Event, association)
end
end
}
x.report('has_many through') {
items.each do |item|
association = item.association(:event_people)
if rails3
ActiveRecord::Associations::CollectionProxy.new(association)
else
ActiveRecord::Associations::CollectionProxy.new(EventPerson, association)
end
end
}
x.report('has_many through through') {
items.each do |item|
association = item.association(:people)
if rails3
ActiveRecord::Associations::CollectionProxy.new(association)
else
ActiveRecord::Associations::CollectionProxy.new(Person, association)
end
end
}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment