Memory size of a hash or other object?

后端 未结 3 924
走了就别回头了
走了就别回头了 2021-02-03 20:47

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

3条回答
  •  无人共我
    2021-02-03 21:06

    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}"
    

提交回复
热议问题