Is there a simple way to get a size of the record (in terms of the disk space it takes) with activerecord (my db is mysql)?
I have found several (1, 2) answers offering a way of doing it with sql, I wonder if there is something built in into Activerecord, like MyRecord.first.bytesize
.
Size of the table would also do, I need an average row size.
The purpose of this is estimating disk space requirements for a database.
UPDATE
I have also found ObjectSpace.memsize_of
require 'objspace'
ObjectSpace.memsize_of(MyRecord.first)
Is the size of the activerecord object equal to the size of the record in the database?
This seems to give the combined size of all the fields. I am casting to String all the fields that do not respond to size
, such as timestamps.
record.attributes.keys.map{ |attr_name| record.send(attr_name)}.inject{|sum, attr| sum + (attr.respond_to?(:size) ? attr.size : attr.to_s.size) }
And here is the comparison of results of these methods for the same record:
- combined size of all attributes (see above): 222
Marshal::dum(record).size
: 2678ObjectSpace.memsize_of(record)
: 128