1

Is there a Rails method to return the data size in bytes of a record?

Let's say I have a table called Item. Is there a method something like @item.data_size that would return "xx bytes"?

I have a mysql database.

Joe Morano
  • 1,715
  • 10
  • 50
  • 114

4 Answers4

3

Not sure if there's a native way of doing it like C, but try this (it might include the size of the class, which is different from the single SQL row):

require 'objspace'
ObjectSpace.memsize_of(@my_item)
Matthew
  • 2,035
  • 4
  • 25
  • 48
0

first way

require "rubygems"
require "knjrbfw"

analyzer = Knj::Memory_analyzer::Object_size_counter.new(my_hash_object)

puts "Size: #{analyzer.calculate_size}"

second way

require 'objspace'

h = {"a"=>1, "b"=>2}
p ObjectSpace.memsize_of(h)       

Measure the memory taken by a Ruby object (by Robert Klemme)

praaveen V R
  • 1,259
  • 1
  • 11
  • 20
0

Fortunately, no. As far as I know it's impossible to determine record size in MySql, as well as in most databases. This is due to following reasons, I'll put only most obvious ones:

  • Record may include association i.e. link to another record in another table and it's completely unclear how to count this, more over it's unclear how to interpret result of such calculation.
  • Record has sort of overhead such indexes, should calculation include it or not?

So, this means such record size will be very approximate and average by nature. If such method would exist it could occur lots of confusion. However it doesn't mean this can't be done at all. Referring this SO answer it is possible to get table size. You could try to seed you database with millions of typical records of fake data e.g. using ffaker gem, get size and divide by record number. This should give very good number for your particular situation.

As a next step you may check is average record size related and does it correlate with object size in memory. This may be pretty interesting.

Cheers!

Community
  • 1
  • 1
sashaegorov
  • 1,821
  • 20
  • 26
-1

Yes you can count the total number of record accessing your model. As example you can try out this code example

@items = Item.all

@items.size or @items.count or @items.length will return the total number of record holds this @items variable. Or directly you can use count on model like Item.count will return total number of record into database.

Rokibul Hasan
  • 4,078
  • 2
  • 19
  • 30
  • I'm sorry, I should have been clearer. By data size, I meant how much information in bytes a record was taking up. – Joe Morano Sep 20 '15 at 04:57