Do more levels of indirection have a performance impact in C

419 Views Asked by At

If I have a structure containing an array of structures.... and on

config.data.item[3].userFunction();

is it better to access with

itemType * item = &config.data.item;

item[3].userFunction();
item[4].userFunction();

or is this just the same as

config.data.item[3].userFunction();
config.data.item[4].userFunction();

Or is there a limit to the number of levels where efficiency is lost, and does compiler optimisation have any effect?

Many thanks in advance for any insight offered.

2

There are 2 best solutions below

3
On

Levels of indirection do have an impact, both in terms of CPU cycles and in readability. However, in your case there is only one level of indirection (the function pointer). Dot operator produces an offset to the location of config at compile time.

Regardless of this, creating a variable to hold the results of common sub-expression is a good idea, especially when you give that variable a meaningful name. In terms of CPU, however, you should see no impact: optimizing compilers are very good these days at detecting and optimizing common sub-expressions, so you should see the same performance either way you code this particular code fragment.

0
On

Even if you have do direct levels of indirection like a->b where there would be a potential cache and performance hit, even innocent looking a.b.c[x].d needs to be examined carefully as that [x] could very well push you out of the cache.

so the answer really is it depends what is in the cache, how big the cache is and what size of structures.

the only real way ever to tell is to test the code in the situation it will be used. You can't even test it in isolation as that would give you false results with cache utilization.

I guess in short, don't even worry about optimizing until you've tested and proven there is an issue and then see whether reorganizing struct fields or avoiding derefs helps...