From 99234f6e7b4ab4b8aabc3d20cfaa2b111fd9653e Mon Sep 17 00:00:00 2001 From: Jonathan del Strother Date: Fri, 23 Aug 2024 10:32:49 +0100 Subject: [PATCH] Micro-optimization to AmazingPrint::ActiveRecord#cast MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit I kept seeing Module#ancestors show up in some profiling involving SemanticLogger. Changing to `foo.is_a?(ActiveRecord::Relation)` and `foo <= ActiveRecord::Base` should be equivalent, but makes `AmazingPrint::Inspector#awesome` 7% faster: ```ruby require "rails" require "active_record" require "amazing_print" require "benchmark/ips" inspector = AmazingPrint::Inspector.new log = { foo: { bar: ["baz"] } } Benchmark.ips do |x| x.report("ancestors.include?") do |times| i = 0 $ap_ancestors = true while i < times inspector.awesome(log) i += 1 end end x.report("class <= ") do |times| i = 0 $ap_ancestors = false while i < times inspector.awesome(log) i += 1 end end x.compare! end ``` ``` ruby 3.2.4 (2024-04-23 revision af471c0e01) [arm64-darwin23] Warming up -------------------------------------- ancestors.include? 4.081k i/100ms class <= 4.289k i/100ms Calculating ------------------------------------- ancestors.include? 40.419k (± 1.5%) i/s - 204.050k in 5.049537s class <= 43.345k (± 1.5%) i/s - 218.739k in 5.047616s Comparison: class <= : 43344.7 i/s ancestors.include?: 40418.6 i/s - 1.07x slower ``` --- lib/amazing_print/ext/active_record.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/amazing_print/ext/active_record.rb b/lib/amazing_print/ext/active_record.rb index 082a187..67762b5 100644 --- a/lib/amazing_print/ext/active_record.rb +++ b/lib/amazing_print/ext/active_record.rb @@ -22,9 +22,9 @@ def cast_with_active_record(object, type) cast = :active_record_instance elsif object.is_a?(::ActiveModel::Errors) cast = :active_model_error - elsif object.is_a?(Class) && object.ancestors.include?(::ActiveRecord::Base) + elsif object.is_a?(Class) && object <= ::ActiveRecord::Base cast = :active_record_class - elsif type == :activerecord_relation || object.class.ancestors.include?(::ActiveRecord::Relation) + elsif type == :activerecord_relation || object.is_a?(::ActiveRecord::Relation) cast = :array end cast