简体   繁体   English

访问说明符和性能

[英]Access specifiers and performance

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? 如果是这样,请解释如何?

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. 在C ++中,访问说明符只是在命名时执行的健全性检查。 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. 因此,它对性能有任何影响确实奇怪。

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. 如果您拥有使用offsetof或公共初始序列的(先前)标准布局类型的用户,则更改成员访问级别的突然未定义行为允许编译器在消除“死”代码时有大量余地。

Even without that, you may have declared public data members in a particularly pessimal order, and private ing one allows a much more favorable layout. 即使没有它,您可能已经以特别粗糙的顺序声明了public数据成员,而private成员允许更有利的布局。 (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. 您不应仅为了重新排序而更改成员的访问说明符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM