1

From a sample ruby code like:

a = 0.0
a = nil  

Now, I would like to know how much storage is occupied by variable 'a' when it's value is '0.0' and when it's value in 'nil'. Thank you.

codemilan
  • 1,072
  • 3
  • 12
  • 32
  • What do you mean by _"storage space occupied by a variable"_? The storage the referenced object is occupying or the storage for storing the variable itself or maybe both? – Stefan Jan 16 '18 at 09:59

1 Answers1

3

The closest to the reality approach I am aware of would be to use memory report as by OS. The below is probably correct for MRI only.

▶ def report
▷   puts 'Memory ' + `ps ax -o pid,rss | grep -E "^[[:space:]]*#{$$}"`.
▷     strip.split.map(&:to_i)[1].to_s + 'KB'  
▷ end  
▶ report
#⇒ Memory 90276KB
▶ a = nil && report
#⇒ Memory 90712KB
▶ a = nil && report
#⇒ Memory 90712KB   NB!!! NOT CHANGED!
▶ a = "a" && report
#⇒ Memory 90908KB
▶ a = "a" && report
#⇒ Memory 91096KB   NB!!! CHANGED!!
▶ a = "a" && report
#⇒ Memory 91388KB   NB!!! CHANGED!!
▶ ObjectSpace.garbage_collect && report
#⇒ Memory 91512KB   NB!!! INCREASED!!!

That said, there is no way to determine how much space would take the object. The amount of memory consumed would be the sum of:

  • amount of memory allocated in the heap
  • RValue required to declare the variable
  • ruby internal memory allocator, that is responsible for handling Ruby Heaps (and the heap they operate)

The latter is unpredictable and it cannot be predicted/calculated based on the data size. It might take zero bytes for the short string when there is a sufficient amount of Ruby slots.

Please note, that RValues are allocated in so-called Ruby Heap and this memory is never returned back to OS. Never means never.

Aleksei Matiushkin
  • 119,336
  • 10
  • 100
  • 160