Skip to content

Instantly share code, notes, and snippets.

@arthurnn
Created February 13, 2014 18:51
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 arthurnn/8981360 to your computer and use it in GitHub Desktop.
Save arthurnn/8981360 to your computer and use it in GitHub Desktop.
require 'active_record'
require 'benchmark'
ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:')
ActiveRecord::Schema.define do
create_table :posts, force: true do |t|
t.integer :comments_count
end
create_table :comments, force: true do |t|
t.integer :post_id
end
end
class Post < ActiveRecord::Base
has_many :comments
end
class Comment < ActiveRecord::Base
belongs_to :post, counter_cache: true
end
10.times do
post = Post.create!
Comment.create!(post: post)
end
record = Post.first
association_name = :comments
if 'prof' == ARGV[0]
require 'stackprof'
mode = ARGV[1] || 'cpu'
StackProf.run(mode: mode.to_sym, out: "tmp/stackprof-#{mode}-reader-rails#{ActiveRecord::VERSION::STRING}.dump") do
100_000.times do
reflection = record.class.reflect_on_association(association_name)
association = reflection.association_class.new(record, reflection)
association.reader
end
end
else
Benchmark.bm do |x|
x.report do
100_000.times do
reflection = record.class.reflect_on_association(association_name)
association = reflection.association_class.new(record, reflection)
association.reader
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment