Created
January 22, 2022 12:14
-
-
Save casperisfine/6bb45a2a2b1a871b9e5a0e47d0e7a62f to your computer and use it in GitHub Desktop.
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 "set" | |
require "objspace" | |
module DeepMemsize | |
class << self | |
def memsize_of(object, seen = Set.new.compare_by_identity) | |
return 0 unless seen.add?(object) | |
size = ObjectSpace.memsize_of(object) | |
object.instance_variables.each { |v| size += memsize_of(object.instance_variable_get(v), seen) } | |
case object | |
when Hash | |
object.each { |k, v| size += memsize_of(k, seen) + memsize_of(v, seen) } | |
when Array | |
object.each { |i| size += memsize_of(i, seen) } | |
end | |
size | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment