Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory size of a hash or other object?

Tags:

ruby

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.

like image 637
bevanb Avatar asked Apr 09 '12 01:04

bevanb


People also ask

How to find memory size of a Python object?

In Python, the most basic function for measuring the size of an object in memory is sys. getsizeof() .

How much memory does a Python list take up?

A list is 32 bytes (on a 32-bit machine running Python 2.7. 3).


2 Answers

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 
like image 132
steenslag Avatar answered Sep 20 '22 23:09

steenslag


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}" 
like image 34
kaspernj Avatar answered Sep 20 '22 23:09

kaspernj