Skip to content

Instantly share code, notes, and snippets.

@taq
Last active December 21, 2015 03:19
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 taq/6241248 to your computer and use it in GitHub Desktop.
Save taq/6241248 to your computer and use it in GitHub Desktop.
Leaky procs
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