Skip to content

Instantly share code, notes, and snippets.

@bogdan
Created September 19, 2024 10:23
Show Gist options
  • Save bogdan/a0e13a4d9393462ed7ce2c0b6ceb4568 to your computer and use it in GitHub Desktop.
Save bogdan/a0e13a4d9393462ed7ce2c0b6ceb4568 to your computer and use it in GitHub Desktop.
require "bundler/inline"
require 'benchmark'
gemfile(true) do
source "https://rubygems.org/"
gem "ostruct"
gem "rails"
gem "sqlite3"
end
require "active_record"
require "logger"
require "minitest/autorun"
ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:")
ActiveRecord::Base.logger = Logger.new($stdout)
ActiveRecord::Schema.define do
create_table :posts, force: true do |t|
t.string :title
end
end
def new_find_finder_class_for(record, stop_class)
current_class = record.class
found_class = nil
loop do
found_class = current_class unless current_class.abstract_class?
break if current_class == stop_class
current_class = current_class.superclass
end
found_class
end
def old_find_finder_class_for(record, stop_class)
class_hierarchy = [record.class]
while class_hierarchy.first != stop_class
class_hierarchy.unshift(class_hierarchy.first.superclass)
end
class_hierarchy.detect { |klass| !klass.abstract_class? }
end
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
end
class Post < ApplicationRecord
end
class Post2 < Post
end
class Post3 < Post2
end
class Post4 < Post3
end
amount = 100000
obj = Post.new
Benchmark.bmbm do |x|
x.report("Old") do
amount.times do
old_find_finder_class_for(obj, ApplicationRecord)
end
end
x.report('New') do
amount.times do
new_find_finder_class_for(obj, ApplicationRecord)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment