On 4/28/2010 11:00 AM, Mariano Martinez Peck wrote:
Hi folks. Sorry for the cross post this time, but I guess it is worth.
In Pharo we were trying to get a way to know the amount of memory (bytes) that an objects is occupying in RAM memory.
For such purpose, Adrian posposed the following method:
Object>>sizeInMemory "Returns the number of bytes used by this object in memory (including its header)"
| headerSize instanceSize | headerSize := (self class indexIfCompact > 0 ifTrue: [ 4 ] ifFalse: [ 8 ]). instanceSize := (self class isVariable ifFalse: [ self class instSize * Smalltalk wordSize ] ifTrue: [ (self basicSize * (self class isBytes ifTrue: [ 1 ] ifFalse: [ Smalltalk wordSize ])) ]). ^ headerSize + instanceSize
Do you think this is correct for all cases?
It's close but not entirely correct. The computation needs to include the extra header word for "large" instances (> 255 bytes). Squeak has three possible header sizes: 1 header word - used by compact classes 2 header words - used by regular classes 3 header words - used by "large" instances BTW, SpaceTally>>spaceForInstancesOf:withInstanceCount: has the correct computation (except for 64 bit :-)
Is there a way to know this but from the VM side also ? how ? I really need it from the VM side :( but I have no idea how to do it.
It's easy to do in the VM, just use this: primitiveByteSize "Answers the number of bytes the receiver occupies" | nbytes| self export: true. oop := self popStack. nbytes := (self sizeBitsOf: oop) + (self extraHeaderBytes: oop). self pushInteger: nbytes. Cheers, - Andreas