4

Which one is the fastest/least memory consuming option 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 also have to mention I will dynamically allocate them. But which one will run faster or be least time consuming?

Thank you!

2
  • There may be minuscule differences which depend on information not provided in the question (e.g. what C implementation you use, including what compiler options, and more importantly what you actually do with the structure). Speed is not a property of C structs. The most common thing I can think of is that the former is going to be a bit bigger on a lot of implementations, perhaps 160 bytes vs 140. Good luck actually detecting any performance difference, though. Commented Dec 19, 2010 at 13:11
  • Why use an array of indexes in the second structure? If you want to address a particular element of string then you just need to know the range of the array. Would it not be simpler to store the size? Commented Dec 19, 2010 at 13:14

3 Answers 3

3
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).

Sign up to request clarification or add additional context in comments.

Comments

2

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

1 Comment

+1 for the first two sentences, but -1 for the last one. As long as the number of items is fixed at 10, this won't be noticeable in any language, but when this number grows big, locality-of-reference effects come into play so performance depends strongly on the task.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.