ruby 散列或其他对象的内存大小?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10068018/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 04:59:17  来源:igfitidea点击:

Memory size of a hash or other object?

ruby

提问by bevanb

What's the best way to get the size of a given hash (or any object really) in bytes in Ruby 1.9.3?

在 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_ofisn't in the documentation for ObjectSpace.

查找特定哈希在 Ruby 中使用的字节数”的解决方案在 1.9.3 中似乎无效,因为ObjectSpacememsize_of的文档中没有。

回答by steenslag

ObjectSpace.memsize_ofdoes workin 1.9.3, documented or not:

ObjectSpace.memsize_of在 1.9.3 中确实有效,无论是否记录:

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

回答by kaspernj

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.

我曾经遇到过同样的问题。您必须注意,实际大小几乎不可能确定,因为这取决于您使用的 VM、VM 的版本等。此外,如果您正在引用一个字符串,该字符串也在其他地方被引用,那么取消设置您的哈希值并不意味着特定包含的字符串也将被取消设置,因为它已经在其他地方被引用了。

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

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

回答by jfanals

An alternative way of having a rough estimateof 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

然后你可以使用一个字符到字节/兆字节的计算器