2

Can changing the access specifier of a class member (say from private to protected) affect the performance (speed of execution) of a class? If so, please explain how?

hermit.crab
  • 852
  • 1
  • 8
  • 20
  • 2
    possible duplicate [here](https://stackoverflow.com/questions/3140294/any-performance-reason-to-put-attributes-protected-private) – Eziz Durdyyev Feb 02 '18 at 15:23

2 Answers2

7

No. If it does, I would consider your compiler to be broken.

Typically, compiled (non-debug) executables contain no information about the layout, access level, and even type of class members. These are simply not required to execute the program, so in usual "don't pay for what you don't use" fashion they are stripped out completely, and thus cannot have any impact on performance.


In theory it could indirectly affect optimizer but I doubt it does in practice. – Slava

Fair point. In C++, access specifiers are just a sanity check performed when naming things. It is always performed last (after overload resolution, name lookup, etc), and only has two outcomes: either the named entity is accessible and all is well, or compilation halts. It cannot change the observable behaviour of a program at all. Thus, it would indeed be very strange that it have any impact on performance whatsoever.

Quentin
  • 62,093
  • 7
  • 131
  • 191
  • In theory it could indirectly affect optimizer but I doubt it does in practice. – Slava Feb 02 '18 at 15:33
  • @Slava indeed, added a section about that :) – Quentin Feb 02 '18 at 15:48
  • How about memory organization? The compiler could probably choose different memory locations for the class member depending on the access specifier to minimize cache misses. Doing so however might increase average fetch time when changing from private to protected access. – hermit.crab Feb 02 '18 at 16:20
2

Changing the access specifier of a data member can affect the layout.

If you have users of a (previously) standard layout type utilising offsetof or a common initial sequence, the sudden undefined behaviour of changing a member's access level allows the compiler large amounts of leeway in eliding "dead" code.

Even without that, you may have declared public data members in a particularly pessimal order, and privateing one allows a much more favorable layout. (or vice-versa)

However, you are free to re-order the declarations of members of your class, and that will have no other observable difference to your code. You should never change the access specifier of a member just for re-ordering purposes.

Caleth
  • 52,200
  • 2
  • 44
  • 75