Skip to content

Instantly share code, notes, and snippets.

@5v3n
Forked from mattetti/gc_test.rb
Created October 4, 2010 19:48
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 5v3n/610299 to your computer and use it in GitHub Desktop.
Save 5v3n/610299 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)
"\n\tstring count: #{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..."
require 'nokogiri'
puts "let's see how nokogiri behaves:"
gc_cost do
nokogiri_builder = Nokogiri::XML::Builder.new
xml = nokogiri_builder.person do |p|
p.name "Sven"; p.phone "555-4321"
end
xml = nokogiri_builder.to_xml
end
@5v3n
Copy link
Author

5v3n commented Oct 4, 2010

added a call to gc_cost with the Nokogiri equivalent of example xml structure

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