Skip to content

Instantly share code, notes, and snippets.

@edisonywh
Last active June 1, 2019 06:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save edisonywh/32ddf65865cc1c91eeedfa929a2d0bec to your computer and use it in GitHub Desktop.
Save edisonywh/32ddf65865cc1c91eeedfa929a2d0bec to your computer and use it in GitHub Desktop.
require 'objspace'
class Foo
def self.memo_hash
@_memo_hash ||= begin
Hash.new(100)
end
end
end
class Bar
def self.hash
Hash.new(100)
end
end
class Baz
BAZ = Hash.new(100)
end
def object_count
ObjectSpace.count_objects[:T_HASH]
end
puts "Init: #{object_count}"
Foo.memo_hash
puts "Foo init: #{object_count}"
100.times do
Foo.memo_hash
end
puts "Foo final: #{object_count}"
Bar.hash
puts "Bar init: #{object_count}"
100.times do
Bar.hash
end
puts "Bar final: #{object_count}"
Baz.hash
puts "Baz init: #{object_count}"
100.times do
Baz.hash
end
puts "Baz final: #{object_count}"
# Result
#
# > Init: 66
# > Foo init: 68
# > Foo final: 69
# > Bar init: 71
# > Bar final: 172
# > Baz init: 173
# > Baz final: 174
#
# As you can see, if I don't memoize it it creates 100 more objects in memory!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment