Last active
June 1, 2019 06:46
-
-
Save edisonywh/32ddf65865cc1c91eeedfa929a2d0bec to your computer and use it in GitHub Desktop.
This file contains 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 '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