Skip to content

Instantly share code, notes, and snippets.

@arthurnn
Created February 15, 2014 00: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 arthurnn/9012245 to your computer and use it in GitHub Desktop.
Save arthurnn/9012245 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
post = Post.first
if 'prof' == ARGV[0]
require 'stackprof'
mode = ARGV[1] || 'cpu'
StackProf.run(mode: mode.to_sym, out: "tmp/stackprof-#{mode}-gist1-#{ActiveRecord::VERSION::STRING}.dump") do
100_000.times do
post.clear_association_cache
post.comments
end
end
else
Benchmark.bm do |x|
x.report do
100_000.times do
post.clear_association_cache
post.comments
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment