Skip to content

Instantly share code, notes, and snippets.

@mattetti
Created October 4, 2010 03:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mattetti/609223 to your computer and use it in GitHub Desktop.
Save mattetti/609223 to your computer and use it in GitHub Desktop.
# hacking some lines to get into the ruby object allocation process...
# Enable the GC profiler:
GC::Profiler.enable
# If our test create too many objects forcing the GC to run,
# we can disable the GC to properly see the object allocation
# GC.disable
def count_string_allocations
strings_before = count(:T_STRING)
yield if block_given?
strings_after = count(:T_STRING)
# let's not create a new string and get the counter confused ;)
# "\n\tstring count: #{strings_after - strings_before}"
strings_after - strings_before
end
def count(type)
ObjectSpace.count_objects[type]
end
def gc_cost(&block)
GC.start # run the GC on the previously allocated objects
yield
GC.start # run the GC on the allocated objects
puts GC::Profiler.result
GC::Profiler.clear
end
puts "#{count_string_allocations {}} strings in memory before starting the test" #rampup
puts "Strings created using a symbol: #{count_string_allocations{ 100.times{ :hello } }}"
puts "Strings created using a string: #{count_string_allocations{ 100.times{ "hello" } }}"
puts "Cost of running the GC"
gc_cost{ 10_000.times { print '.' } }
# install builder if not already available ($ gem install builder)
require 'builder'
puts "Cost of running the GC on 1 builder object"
gc_cost do
builder = Builder::XmlMarkup.new
xml = builder.person { |b| b.name("Matt"); b.phone("555-1234") }
end
puts "ouch..."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment