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