Skip to content

Instantly share code, notes, and snippets.

@seanwalbran
Created July 31, 2012 20:30
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 seanwalbran/8c690d9ae08357f2b3cd to your computer and use it in GitHub Desktop.
Save seanwalbran/8c690d9ae08357f2b3cd to your computer and use it in GitHub Desktop.
jeremy-less-pathological-gcdata.rb
HTML_ESCAPE = { '&' => '&amp;', '>' => '&gt;', '<' => '&lt;', '"' => '&quot;' }
def original(s)
s.gsub(/[&"><]/n) { |special| HTML_ESCAPE[special] }
end
def new_range(s)
s.encode(s.encoding, :xml => :attr)[1...-1]
end
def new_tr(s)
s.encode(s.encoding, :xml => :attr).tr!('"', '')
end
def new_slice(s)
t = s.encode(s.encoding, :xml => :attr)
t[1, t.size - 1]
end
def new_delete(s)
s.encode(s.encoding, :xml => :attr).delete!('"')
end
def new_gsub(s)
s.encode(s.encoding, :xml => :attr).gsub!(/^"|"$/o, '')
end
def bench(method, string, times = 1000)
GC.start
GC.disable
t0 = Time.now
counts = ObjectSpace.count_objects
o0 = counts[:TOTAL] - counts[:FREE]
s = GC.malloc_allocated_size if GC.respond_to?(:malloc_allocated_size)
c = GC.count
times.times do
send method, string
end
elapsed = Time.now - t0
counts = ObjectSpace.count_objects
allocated = counts[:TOTAL] - counts[:FREE]
allocated_size = (GC.malloc_allocated_size - s).to_f/(1024.0*1024.0) if GC.respond_to?(:malloc_allocated_size)
allocated_size ||= -1.0
garbage_collections = GC.count - c
GC.enable
[elapsed, allocated, allocated_size, garbage_collections]
end
s = '<script>alert("foo & bar & baz");</script> Laborum next level organic nihil cardigan.'
[s, s * 10, s * 100, s * 1000].each do |string|
%w(original new_range new_tr new_slice new_delete new_gsub).each do |method|
elapsed, allocated, allocated_size, garbage_collections = bench method, string
puts "%10s %5d chars: %7.1fms elapsed %10d objects %.3f MB %5d collections" % [method, string.bytesize, elapsed * 1000, allocated, allocated_size, garbage_collections]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment