Skip to content

Instantly share code, notes, and snippets.

@jimweirich
Last active December 14, 2015 13:28
Show Gist options
  • Save jimweirich/5093489 to your computer and use it in GitHub Desktop.
Save jimweirich/5093489 to your computer and use it in GitHub Desktop.
Test of memory usage when creating a lot of slices of a large array.
# I'm guessing that MRI and JRuby don't copy the array elements
# when making a slice, they just reference the original copy with
# new index bounds.
$ rvm use ruby-1.9.3-p286
Using /Users/jim/.rvm/gems/ruby-1.9.3-p286
$ ruby mem.rb
Before: 12716
After: 12744
$ rvm use jruby
Using /Users/jim/.rvm/gems/jruby-1.7.3
$ ruby mem.rb
Before: 95556
After: 95780
# However, it does look like Rubinius does copy
# the actual array elements.
$ rvm use rbx
Using /Users/jim/.rvm/gems/rbx-head
$
$ ruby mem.rb
Before: 36824
After: 856120
def mem_usage
process_id = $$.to_s
lines = `ps -v`.split(/\n/)
lines.each do |line|
fields = line.split
if fields[0] == process_id
return fields[7].to_i
end
end
0
end
kb = 1024
mb = kb*kb
a = Array.new(mb)
puts "Before: #{mem_usage}"
slices = (1..100).map { |i| a[i..-1] }
puts "After: #{mem_usage}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment