Last active
December 21, 2015 03:19
-
-
Save taq/6241248 to your computer and use it in GitHub Desktop.
Leaky procs
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
class Printer | |
@messages = [] | |
def self.print | |
puts yield | |
end | |
def self.lazy_print(val=nil,&block) | |
@messages << val || block | |
end | |
def self.messages | |
@messages | |
end | |
def self.clear | |
@messages = [] | |
end | |
end | |
class Foo | |
def initialize(i) | |
Printer.print { "hey #{i}" } | |
end | |
end | |
class LeakyFoo | |
def initialize(i) | |
Printer.lazy_print -> { "hey #{i}" } | |
#Printer.lazy_print String.new("hey #{i}") | |
end | |
end | |
100.times { |i| Foo.new i } | |
100.times { |i| LeakyFoo.new i } | |
GC.start # first call, will release all LeakyFoo with Strings on 2.x | |
puts "Foo count = #{ObjectSpace.each_object(Foo).count}" | |
puts "LeakyFoo count = #{ObjectSpace.each_object(LeakyFoo).count}" | |
GC.start # this will release all LeakyFoo with Strings on 1.9 | |
puts "LeakyFoo count = #{ObjectSpace.each_object(LeakyFoo).count}" | |
# now we want all of them to go away | |
Printer.clear | |
GC.start | |
puts "LeakyFoo count = #{ObjectSpace.each_object(LeakyFoo).count}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment