Last active
May 11, 2025 12:37
-
-
Save alekseyl/d7aa5539aec2cd507b2091ab0700742b to your computer and use it in GitHub Desktop.
CPU profiling method comparing eager_load VS preload aproaches
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def compare_cpu_general( scope, base_collection_size, nesting) | |
ids = scope.ids | |
ActiveRecord::Base.logger.silence do | |
Benchmark.bmbm do |benchmark| | |
benchmark.report("eager_load") do | |
50.times do | |
# sample(base_collection_size + 1) and limit(base_collection_size) | |
# added to imitate real limit for eager_load, so it would be obligated to use 2 queries instead of one | |
# for more read here: https://medium.com/p/5ce11870de62 | |
scope.where(id: ids.sample(base_collection_size + 1)).limit(base_collection_size).eager_load(nesting).load | |
end | |
end | |
benchmark.report("preload") do | |
50.times do | |
# for the sake of scopes equality | |
scope.where(id: ids.sample(base_collection_size + 1)).limit(base_collection_size).preload(nesting).load | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment