Skip to content

Instantly share code, notes, and snippets.

@bryanp
Created October 17, 2019 00:56
Show Gist options
  • Save bryanp/bd28b18f7facc19f0819a27c63f3b408 to your computer and use it in GitHub Desktop.
Save bryanp/bd28b18f7facc19f0819a27c63f3b408 to your computer and use it in GitHub Desktop.
Ruby allocation calling mixin
module Foo
def foo
bar
end
def bar
end
end
class Whatever
include Foo
end
class SomethingElse
def foo
bar
end
def bar
end
end
something_else = SomethingElse.new
start = GC.stat(:total_allocated_objects)
something_else.foo
puts GC.stat(:total_allocated_objects) - start
# => 0 (this is what I expected)
whatever = Whatever.new
start = GC.stat(:total_allocated_objects)
whatever.foo
puts GC.stat(:total_allocated_objects) - start
# => 2 (huh)?
@ioquatix
Copy link

Using rspec-memory to capture this but didn't get any clear picture.

#!/usr/bin/env ruby

require 'rspec/memory/trace'

module Foo
  def foo
    bar
  end

  def bar
  end
end

class Whatever
  include Foo
end

class SomethingElse
  def foo
    bar
  end

  def bar
  end
end

something_else = SomethingElse.new
start = GC.stat(:total_allocated_objects)
something_else.foo
puts GC.stat(:total_allocated_objects) - start
# => 0 (this is what I expected)

trace = RSpec::Memory::Trace.new([])

trace.capture do
	whatever = Whatever.new
	whatever.foo
end

pp trace

gives

0
#<RSpec::Memory::Trace:0x00007f96ef07e7d8
 @allocated={},
 @ignored={Whatever=>#<struct RSpec::Memory::Allocation count=1, size=0>},
 @klasses=[],
 @retained={},
 @total=#<struct RSpec::Memory::Allocation count=1, size=0>>

@ioquatix
Copy link

That means it can't be a Ruby object but some internal data structure allocated by Ruby.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment