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.
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.
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)
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)
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:
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!
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.