Last active
May 24, 2025 17:09
-
-
Save alekseyl/a632f03bea6c24eb17611f92e0105cdb to your computer and use it in GitHub Desktop.
Memory 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
require 'memory_profiler' | |
require 'terminal-table' | |
def compare_ram(scope, base_collection_size, nesting) | |
ids = scope.ids | |
ids_sample = ids.sample(base_collection_size) # it should be the same id for both tests, since we comparing memory consumption | |
# just to keep from memory profiler objects oblivion, and get retain numbers correctly | |
el, pr = [] | |
preload = MemoryProfiler.report do | |
pr = scope.where(id: ids_sample).preload(nesting).load | |
end | |
eager_load = MemoryProfiler.report do | |
el = scope.where(id: ids_sample).eager_load(nesting).load | |
end | |
rows = {preload:, eager_load:}.to_a | |
rows.sort_by!{ |(_,profile)| profile.total_retained_memsize } | |
# [ [name, profile] , []] | |
smlst = rows[0].last | |
rows.map! do |(name, profile)| | |
[ | |
name, | |
"#{profile.total_retained_memsize.to_fs(:human_size)}"\ | |
"(objects: #{profile.total_retained}, ratio: #{(profile.total_retained_memsize.to_f/smlst.total_retained_memsize).floor(2)} )", | |
"#{profile.total_allocated_memsize.to_fs(:human_size)}"\ | |
"(objects: #{profile.total_allocated}, ratio: #{(profile.total_allocated_memsize.to_f/smlst.total_allocated_memsize).floor(2)} )" | |
] | |
end.map!(&:flatten) | |
puts Terminal::Table.new(:headings => ['Methods', 'Retained', 'Allocated'], :rows => rows) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment