1
votes

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: 2678
  • ObjectSpace.memsize_of(record): 128
1
There is no built-in way to do this with ActiveRecord. - Jordan Running
I have implemented some quick solution that does what I need and I packed it into a gem . I will probably improve on it later... - bosskovic

1 Answers

2
votes

An approximation of size can be found by using:

Marshal::dump(obj).size

Since you said, its for database sizing - The dump has name of classes and instance variables - it may be bit of overhead compared to absolute record size.

You may want to look at this answer for getting MySQL DB size - Database size calculation? and How to Get True Size of MySQL Database?

Based on number of entities currently stored in DB, and size thus determined using above methods - you can extrapolate for sizing.