views:

68

answers:

3

I would like to know what the best way (performance wise) to access a large data structure is. There are about hundred ways to do it but what is the most accessible for the compiler to optimize?

One can access a value by

foo[someindex].bar[indexlist[i].subelement[j]].baz[0]

or create some pointer aliases like

sometype_t* tmpfoo = &foo[someindex];
tmpfoo->bar[indexlist[i].subelement[j]].baz[0]

or create reference aliases like

sometype_t &tmpfoo = foo[someindex];
tmpfoo.bar[indexlist[i].subelement[j]].baz[0]

and so forth...

+1  A: 

All of the three you described here will compile (with a decent compiler) to the same thing.

Keith Randall
+5  A: 

Premature optimization is the root of all evil. Write clear code, if it's too slow, profile it and see where the time is spent and optimize there.

That being said, 99% chance that the compiler generates the same code for all three of those examples.

miked
A: 

As a personal preference, I generally find it easier to read and understadn if there are fewer nested levels to traverse. Thus, I tend to use the ...

SomeType  *pSomeType = &asManyLevelsAsItMakesSense[someIndex];
pSomeType->subSomeNestedLevels = ...;

I find this particularly useful when dealing with deep nested structures in loops. Identify the invariant nested parts and hoist it out of the loop.

SomeType  *pSomeType = &...;
for (i = 0; i < N; i++)
    pSomeType->field[i] = ...;

As always, it is worth your while to know your compiler and what it actually generates. Sometimes you may be stuck with a compiler for your project that does no optimization at all and so little things like this can make a difference (but don't assume that it will).

Sparky