开发者

Array of structures or structure of array in C

Which one is the fastest/least memory consuming option of these two:

st开发者_开发问答ruct {
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 also have to mention I will dynamically allocate them. But which one will run faster or be least time consuming?

Thank you!


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

will introduce padding for each a[] item.

The second solution will introduce padding only once.

If you are going to allocate a large number of items in a[] then you will pay the price of having a larger domain to cover (not to mention the additional dereferencing).


Don't bother with premature optimization. Use the one easier to understand/maintain. Since this is C, performance difference will barely be noticeable.


The 2nd would probably be smaller memory-wise simply because sizeof struct above is 8, not 5 because of padding (provided that int is 32-bit).

As for which is faster, I'd say it would depend on what you're doing; the 2nd is a typical example of data-oriented design (not to be confused with data-driven design). Please see this article: http://gamesfromwithin.com/data-oriented-design

EDIT: That said, I agree with Milan here (at the other answer) -- don't bother optimizing prematurely, or at all. Both are fast enough; I didn't emphasize this earlier because I figured you might need it for an embedded system, where this could matter.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜