Some classes have a size
method that returns the object's size on memory. For instance:
1.size
returns 4, which means it takes 4 bytes to store a Fixnum object (1
's class). The same goes for Bignum
objects: 4294967296.size
returns 8.
ActiveRecord::Base
doesn't seem to have an equivalent method. What can I do if want do measure how much memory my ActiveRecord
s take?
The size
method returns the number of bytes in the machine representation of the number. It doesn't necessarily (and doesn't in practice) give you the the actual memory usage. While a Fixnum does indeed take 4 Bytes of memory (in MRI, other Ruby implementations differ), a Bignum takes more memory as it it an actual Ruby object.
Similarly, other classes which implement a size
method like String
, Array
, or Hash
doesn't return memory usage but the number of elements they contain (characters, array elements, keys respectively).
Generally, you can't really determine how much memory an object takes in memory (well, you can, but it would not give you the information you want). An ActiveRecord object refers to a large number of other objects like Hashes, Strings, Symbols, .... You would probably need to count them too, probably even recursive. Then you somehow need to deal with references to the same objects, and somewhere define the boundary of your object tree until you end up re-implementing most of the garbage collector.
So in the end, it turns out, you can't practically determine the memory usage of a single ActiveRecord object and you probably shouldn't. For more details, please also refer to a similar answer of mine on another question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With