Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

memory and efficiency difference between normal array declaration and array declared inside a structure

When declaring arrays in C they can be declared normally like:

int arr[10]

or they can also be declared inside a structure like:

struct structArr{
   int sArr[10];
}s1;
  1. Will there be any memory or space tradeoff when using s1.sArr[] instead of arr[], if so why?
  2. Is any one form more efficient and faster than the other?

What I personally think is that arr[] would be faster than s1.sArr[] but I don't know whether I am correct or not moreover I don't have a technical answer for it.

like image 587
palash kulshreshtha Avatar asked Jan 15 '23 14:01

palash kulshreshtha


2 Answers

I wouldn't expect there to be any difference, no.

The compiler "knows" that the offset of the sArr field from the base address of s1 is 0, so I would guess that accesses can be done using the exact same sequence of instructions.

Of course, wrapping the array in a structure makes it possible to assign and pass/return it by value, which can be nice benefits.

like image 120
unwind Avatar answered Jan 27 '23 02:01

unwind


The answer to your question depends upon the compiler and the optimizations.

With a recent GCC compiler with at least -O1 optimization, arr[] won't be faster than s1.sArr[]. Actually, if for some reason (e.g. its other fields) s1 is more aligned than arr is, then it could happen (because of cache effects) that s1.sArr[] might be slightly better (e.g. because more aligned to cache line size). But really from a performance point of view using arr[] or s1.sArr[] is (nearly mostly) the same.

For readability reasons things can be different. You may want to pack related items into some struct. (And you may want to avoid having too much variable names).

like image 22
Basile Starynkevitch Avatar answered Jan 27 '23 02:01

Basile Starynkevitch