Skip to content

Instantly share code, notes, and snippets.

@iogakos
Last active December 19, 2015 08:39
Show Gist options
  • Save iogakos/5927596 to your computer and use it in GitHub Desktop.
Save iogakos/5927596 to your computer and use it in GitHub Desktop.
Strange behavior of Ruby's GC. ## Careful !! The following script requires ~40Mb of your virtual memory address space.
## Careful !!
# The following script requires ~40Mb of your virtual memory address space.
vm_before = File.read("/proc/#{$$}/status").match(/^VmSize:\s*(\d*)/)[1].to_i
def vm_used(vm_before)
File.read("/proc/#{$$}/status").match(/^VmSize:\s*(\d*)/)[1].to_i - vm_before
end
# w block
def gsub_w(s)
["la ", "ko "].each{ |t| s.gsub!(/#{t}/){ "" } }
end
# w/o block
def gsub_wo(s)
["la ", "ko "].each{ |t| s.gsub!(/#{t}/, "") }
end
########
#
# str_gsub() without using block
p [:before_string_build, vm_used(vm_before)]
s = ""
3495253.times { |i| s << "la " } # ~10 Mb
3495253.times { |i| s << "ko " } # ~10 Mb
p [:after_string_build, vm_used(vm_before)]
p [:before_gsub_wo_block, vm_used(vm_before)]
gsub_wo(s)
# VmSize goes wild here !!!!
p [:after_gsub_wo_block, vm_used(vm_before)]
GC.start
########
#
# str_gsub() using block
p [:before_string_build, vm_used(vm_before)]
s = ""
3495253.times { |i| s << "la " } # ~10 Mb
3495253.times { |i| s << "ko " } # ~10 Mb
p [:after_string_build, vm_used(vm_before)]
p [:before_gsub_wo_block, vm_used(vm_before)]
gsub_w(s)
p [:after_gsub_wo_block, vm_used(vm_before)]
p [:end, vm_used(vm_before)]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment