What\'s the best way to get the size of a given hash (or any object really) in bytes in Ruby 1.9.3?
The solution to \"Find number of bytes a particular Hash is using in
An alternative way of having a rough estimate of the size of a hash is to convert it into a string and count the number of characters, each character will be a byte.
hash = {hello: "world"}
=> {:hello=>"world"}
hash.to_s
=> "{:hello=>\"world\"}"
hash.to_s.size
=> 17
Then you can use a characters to bytes/megabytes calculator
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}"