1

I want to store 3 properties of 1000 rectangles. I can do that in two different ways. I can use a structure or an array, but I try to find out which solution uses least memory. Here the code:

struct Figure {
    unsigned int color;
    virtual void foo() {}
};

struct Rectangle : public Figure {
    unsigned int width,height;
};

int main() {
    Rectangle r[1000];
    unsigned int r2[1000][3]; //This take less memory, The first entry is rectangle number
                        // the next is color, width and height
std::cout<<"Type name is "<< typeid(r[0]).name() <<sizeof(r2)<<" "<<sizeof(r)<<std::endl;
return 0;
}

The output is:

Type name is 9Rectangle12000 24000

As you can see an array of objects of a structure uses twice as much memory as a plain array. Why is it so? I expected that an array of structures in my case would use more memory because of the polymorphic structure, but not that much.

user2304458
  • 363
  • 1
  • 2
  • 11
  • My guess is that this has to do with padding byte and member functions (not present in the unsigned int array) – Clonk Jun 12 '18 at 15:32

1 Answers1

2
  1. Your struct has virtual functions, so there's a vptr in there.

  2. There may be padding between members and/or at the end of the struct for alignment purposes.

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70
  • Alignment definitely plays a part, you can verify by comparing 4 unsigned ints instead of 3. The array size grows but the struct size stays the same. Moreso, comparing a non-polymorphic struct with 4 unsigned ints to the same equivalent array produces no overhead. – Rotem Jun 12 '18 at 15:34
  • I agree that it has something to do with padding, but what about the polymorphic structure? Shouldn't my array of Rectangles not always use more memory than an equivalent array? In my case even with 4 unsigned int, I get an overhead, the array uses only 16000 bytes. – user2304458 Jun 12 '18 at 15:50