0

Is there any difference in memory usage / execution speed between e.g.

struct test
{
   int a;
   float b;
   char c;
}; 

test ar[30];

and

int arr1[30];
float arr2[30];
char arr3[30];

? Lets pretend, that we are not talking about work comfort or programmer sided things, only speed of execution / memory usage.

encoree1337
  • 317
  • 2
  • 15
  • possible duplicate of [Why isn't sizeof for a struct equal to the sum of sizeof of each member?](http://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member) – Cory Kramer Oct 14 '14 at 20:44
  • 1
    Yes, there can be a difference in performance, but it heavily depends on the usage case (as always). The best way to know: measure your use case. – dyp Oct 14 '14 at 20:45

3 Answers3

8

In terms of memory usage definitely.

When you allocate test ar[30] you are actually allocating:
int - float - char - (padding) - int - float - char - ...

While in your second example you are allocating:
int - int - int - .... - float - float - ... - char - ...

So the layout in your memory is completely different, which will have an impact on your performance (depending on what you do OFC)

UnholySheep
  • 3,967
  • 4
  • 19
  • 24
2

In term of execution performance (speed), there is a difference because of the CPU cache; even if you ask the compiler to optimize.

If all the members of a given structure are accessed nearly together, the locality is increased, and you get less cache misses.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
1

In terms of memory size, the compiler may add padding to the struct to align memory, so it is possible that sizeof(test) > sizeof(arr1) + sizeof(arr2) + sizeof(arr3)

fhsilva
  • 1,217
  • 1
  • 9
  • 17