sizeof(Class)/sizeof(Object)

N

Nikolai Weibull

I would like to figure out how much memory a certain class or object
will/is consuming. Is there an easy way? Is there a hard way?
The reason I ask is because I want to keep several hundred thousand
instances of an object much like the following one:

class A
def initialize
@a = @b = @c = @d = nil
@e = 1
end
end

nikolai
 
C

Charles Mills

Nikolai said:
I would like to figure out how much memory a certain class or object
will/is consuming. Is there an easy way? Is there a hard way?
The reason I ask is because I want to keep several hundred thousand
instances of an object much like the following one:

class A
def initialize
@a = @b = @c = @d = nil
@e = 1
end
end

Instance variables are stored in a hash table associated with each
object. See rb_ivar_set() in variable.c. So basically each instance
will take up the size of struct RObject - which is 20 bytes on a 32bit
machine, plus the size of the hash table (see st.h), plus something
else I am probably missing. As far as I know st.h doesn't provide any
means of calcing the number of bytes used by the hash.
Is there a way to do this?

Also, objects with no instance variables don't create a hash table to
store instance variables...

-Charlie
 
R

Robert Klemme

Charles Mills said:
Instance variables are stored in a hash table associated with each
object. See rb_ivar_set() in variable.c. So basically each instance
will take up the size of struct RObject - which is 20 bytes on a 32bit
machine, plus the size of the hash table (see st.h), plus something
else I am probably missing. As far as I know st.h doesn't provide any
means of calcing the number of bytes used by the hash.
Is there a way to do this?

Also, objects with no instance variables don't create a hash table to
store instance variables...

So if there was only one instance var an optimization could be to store them
in a hash in the instance's class. This could work for multiple ivars as
well but then there is the array overhead. Hm...

class Foo
@ivar = {}

def initialize
cl = self.class
ObjectSpace.define_finalizer(self) {|id| cl.remove id}
end

def bar=(x) self.class.set_val(id, x) end
def bar; self.class.get_val(id) end

def self.set_val(id, val)
@ivar[id] = val
end

def self.get_val(id)
@ivar[id]
end

def self.remove(id)
puts "removing #{id}"
@ivar.delete id
end
end

Just some thoughts in code...

robert
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,733
Messages
2,569,440
Members
44,832
Latest member
GlennSmall

Latest Threads

Top