optional reduction of overhead for classes
    xs0 
    xs0 at xs0.com
       
    Tue Apr 18 07:23:45 PDT 2006
    
    
  
clayasaurus wrote:
> Tom S wrote:
>> clayasaurus wrote:
>>> class EntityData
>>> {
>>>   float x, y;
>>> }
>>>
>>> ------------------------------------------------------------------------
>>>
>>> My question is, how much memory does EntityData use before allocation 
>>> (4-bytes?), and how much does it use after allocation (4+4+4 bytes 
>>> total?).
>>
>> Well, before allocation, your EntityData doesn't really exist, only a 
>> null reference, which takes 4 bytes on 32 bit systems. 
> IIRC, you can
>> check the size of an object thru .classinfo.init.length.
> 
> Thanks for that :) After I allocate it, it says it uses 16 bytes. Since 
> the size of a float is only four bytes and the null reference is  4 
> bytes, would that be 4+4+4 = 12? I wonder where the other 4 bytes come 
> from, maybe typeinfo?
I think that there are
- 4 bytes for pointer to the virtual method table (you inherit from 
Object, so there are methods)
- 4 bytes for pointer to synchronization data (because you could use it, 
even if you don't)
- 8 bytes for two floats
The reference to the object costs additional 4 bytes.
Assuming the above is everything you need, you could use a struct 
instead, saving the first 8 bytes..
Finally, I think that the current GC will allocate 1 byte more than 
strictly needed, so the actual amount of memory used per instance of 
EntityData will be 32 bytes (for class) or 16 bytes (for struct).
Another option would be to include the data in one version of the class, 
and a pointer to it in another (dependant) version. When you want to 
share the data, just set the pointer of EntityDependant to data of an 
Entity instance.
struct EntityData
{
     float x,y;
}
class EntityBase {
     abstract void draw();
}
class Entity : EntityBase {
     EntityData data;
     void draw() {
         glDraw(data.x, data.y);
     }
}
class EntityDependant : EntityBase {
     EntityData *data;
     void draw() {
         glDraw(data.x, data.y);
     }
}
That way, you have no overhead if you use an Entity, and save 4 bytes 
(but lose some speed) for each instance of EntityDependant.
xs0
    
    
More information about the Digitalmars-d-learn
mailing list