Skip to content

Instantly share code, notes, and snippets.

@JoshCheek
Created October 6, 2022 13:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JoshCheek/6993090b14dd866170c2495cfad8d2e9 to your computer and use it in GitHub Desktop.
Save JoshCheek/6993090b14dd866170c2495cfad8d2e9 to your computer and use it in GitHub Desktop.
Figuring out where objects are coming from
# followup for https://twitter.com/kirill_shevch/status/1577930057728856064
require 'objspace'
require 'json'
def some_code
[ 10_000.times.map { "hi" },
5_000.times.map { "there" },
JSON.load('{ "omg": 123, "wtf": true, "bbq": 23.45 }'),
]
end
ObjectSpace.trace_object_allocations do
_ = some_code # saving to a variable so they don't get gc'd
ObjectSpace
.each_object(String)
.to_a # eager load them so it doesn't consider strings created during iteration
.filter_map {
file = ObjectSpace.allocation_sourcefile _1
line = ObjectSpace.allocation_sourceline _1
file && line && "#{file}##{line}"
}
.tally
.sort_by { -_2 }
# => [["program.rb#4", 10000],
# ["program.rb#5", 5000],
# ["/Users/josh/.gem/ruby/3.0.2/gems/json-2.6.1/lib/json/common.rb#216",
# 3],
# ["program.rb#6", 1]]
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment