Memory size of a hash or other object?
ObjectSpace.memsize_of
does work in 1.9.3, documented or not:
puts RUBY_VERSION #=>1.9.3
require 'objspace'
p ObjectSpace.memsize_of("a"*23) #=> 23
p ObjectSpace.memsize_of("a"*24) #=> 24
p ObjectSpace.memsize_of("a".*1000) #=> 1000
h = {"a"=>1, "b"=>2}
p ObjectSpace.memsize_of(h) #=> 116
I once had the same problem. You have to be aware, that the real size is almost impossible to determine, since it depends on which VM you are using, which version of the VM and so on. Also, if you are referencing a string, that is also referenced somewhere else, then unsetting your hash doesn't mean that the specific contained string will also be unset, since it is already referenced somewhere else.
I once wrote an analyzer to count the estimated size of objects, by going through all contained objects in the given object. Get inspired to write your own:
https://github.com/kaspernj/knjrbfw/blob/master/lib/knj/memory_analyzer.rb#L334
Mine works like this:
require "rubygems"
require "knjrbfw"
analyzer = Knj::Memory_analyzer::Object_size_counter.new(my_hash_object)
puts "Size: #{analyzer.calculate_size}"