Array of structures or array structures in C

Which one is the fastest / least memory accessible version of these two:

struct { int index; char string[10]; } a[10]; 

or

 struct { int index[10]; char string[10][10]; } a; 

The first one is clearly easier to use and implement. I should also mention that I will dynamically distribute them. But which one will work faster or be the least time consuming?

Thanks!

+4
source share
3 answers
 struct { int index; char string[10]; } a[10]; 

introduces addition for each element a[] .

The second solution will introduce padding only once.

If you are going to highlight a large number of elements in a[] , then you will pay the price for expanding a larger domain (not to mention the additional dereferencing).

+3
source

Do not bother with premature optimization. Use one that is easier to understand / maintain. Since this is C, the performance difference is barely noticeable.

+2
source

The second one will probably be smaller in memory simply because the sizeof struct above is 8 and not 5 due to padding (assuming int is 32-bit).

As for which is faster, I would say that it will depend on what you do; the second is a typical example of a data-oriented design (not to be confused with a data-based design). See This Article: http://gamesfromwithin.com/data-oriented-design

EDIT: I said I agree with Mill (with a different answer) - don't bother optimizing prematurely or at all. Both are fast enough; I did not emphasize this before because I decided that you would need it for an embedded system where it might matter.

+1
source

Source: https://habr.com/ru/post/1332661/


All Articles