Sahil
Sahil

Reputation: 504

Finding memory allocation of Ruby Arrays

I wanted to find out the memory consumed (in bytes) by data types. I called size method on an integer. Since I am running a 64 bit machine, it returned 8.

1.size # => 8

Similarly, for strings and arrays, it returned 1 byte per character/integer.

'a'.size # => 1
['a'].size # => 1
['a', 1].size # => 2
  1. Why is there no size method for float?
  2. Shouldn't heterogeneous arrays like ['a', 1] return 1 + 8 = 9 bytes (1 for char, 8 for integer)?
  3. Is it correct to call size to check memory allocated to ruby data types?

Upvotes: 2

Views: 3733

Answers (3)

Gagan Gami
Gagan Gami

Reputation: 10251

I think you are looking for MRI memory usage. Ruby has ObjectSpace : The objspace library extends the ObjectSpace module and adds several methods to get internal statistic information about object/memory management.

You need to require 'objspace' to use this extension module.

Here is what you will get:

 > require 'objspace'
 => true 
 > ObjectSpace.memsize_of(Array)
 => 5096 
 > ObjectSpace.memsize_of(Hash)
 => 3304 
 > ObjectSpace.memsize_of(String)
 => 6344 
 > ObjectSpace.memsize_of(Integer)
 => 1768 

Note: Generally, you SHOULD NOT use this library if you do not know about the MRI implementation. Mainly, this library is for (memory) profiler developers and MRI developers who need to know about MRI memory usage.

Upvotes: 9

Jikku Jose
Jikku Jose

Reputation: 18804

Array#size returns the count of elements of the Array rather than memory allocated.

Upvotes: 2

shivam
shivam

Reputation: 16506

These are two different methods that serves different purpose for two different data types.

In eg 1, you are applying size to fixnum. This method:

Returns the number of bytes in the machine representation of fix.

source: http://www.ruby-doc.org/core-2.2.0/Fixnum.html#method-i-size

However when used with array, size is alias for length. Here: http://www.ruby-doc.org/core-2.1.2/Array.html#method-i-size. Which:

Returns the number of elements in self. May be zero.

Upvotes: 4

Related Questions