开发者

Best way to access nested data structures?

开发者 https://www.devze.com 2023-01-02 09:20 出处:网络
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?

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

开发者_JAVA百科
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...


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.


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


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

0

精彩评论

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