Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the size of a ruby object in mb in Rails?

I want to query an ActiveRecord model, modify it, and calculate the size of the new object in mb. How do I do this?

like image 230
Eric Baldwin Avatar asked May 05 '15 00:05

Eric Baldwin


1 Answers

The size of data rows in a database as well as the object size of ruby objects in memory are both not readily available unfortunately.

While it is a bit easier to get a feeling for the object size in memory, you would still have to find all objects which take part of your active record object and thus should be counted (which is not obvious). Even then, you would have to deal with non-obvious things like shared/cached data, class overhead, which might be required to count, but doesn't have to.

On the database side, it heavily depends on the storage engine used. From the documentation of your database, you can normally deduct the storage requirements for each of the columns you defined in your table (which might vary in case of VARCHAR, TEXT, or BLOB columns. On top of this come shared resources like indexes, general table overhead, ... To get an estimate, the documented size requirements for the various columns in your table should be sufficient though

Generally, it is really hard to get a correct size for complex things like database rows or in-memory objects. The systems are not build to collect or provide this information.

Unless you absolutely positively need to get an exact data, you should err on the side of too much space. Generally, for databases it doesn't hurt to have too much disk space (in which case, the database will generally run a little faster) or too much memory (which will reduce memory pressure for Ruby which will again make it faster).

Often, the memory usage of Ruby processes will be not obvious. Thus, the best course of action is almost always to write your program and then test it with the desired amount of real data and check its performance and memory requirements. That way, you get the actual information you need, namely: how much memory does my program need when handling my required dataset.

like image 130
Holger Just Avatar answered Nov 14 '22 20:11

Holger Just