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.
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.
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:
RValue
required to declare the variableThe 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 RValue
s are allocated in so-called Ruby Heap and this memory is never returned back to OS. Never means never.