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 Ruby" does not appear to be valid in 1.9.3, because memsize_of
isn't in the documentation for ObjectSpace.
In Python, the most basic function for measuring the size of an object in memory is sys. getsizeof() .
A list is 32 bytes (on a 32-bit machine running Python 2.7. 3).
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}"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With