将属性设置为受保护/私有的任何性能原因吗?
我在学校“学习”了 C++,但有几件事我不知道,比如编译器可以在哪里或什么优化,似乎我已经知道 inline
和 const
可以提高一点...
如果性能很重要(例如游戏编程),是否将类属性设置为非公共(私有
或受保护) 允许编译器生成更优化的代码?
因为我以前的所有老师都说它更“安全”或“防止不需要或授权的类访问/行为”,但最后,我想知道将属性非 public
是否可以限制范围,从而固定事物。
我不批评我的老师(应该),但我上的编程课不是很高级......
I "learned" C++ at school, but there are several things I don't know, like where or what a compiler can optimize, seems I already know that inline
and const
can boost a little...
If performance is an important thing (gaming programming for example), does putting class attributes not public
(private
or protected
) allow the compiler to make more optimized code ?
Because all my previous teacher were saying was it's more "secure" or "prevent not wanted or authorized class access/behavior", but in the end, I'm wonder if putting attributes not public
can limit the scope and thus fasten things.
I don't criticize my teachers (should I), but the programming class I was in wasn't very advanced...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
老师们正确地告诉您使用 private 和 protected 来隐藏实现,并教您有关信息隐藏的知识,而不是提出有问题的性能优化。尝试首先考虑适当的设计,然后考虑性能,在 99% 的情况下,这将是更好的选择(即使在性能关键场景中)。性能瓶颈可能会出现在许多不可预测的情况下,如果您的设计合理,则更容易出现性能瓶颈。
然而,要直接回答你的问题:范围的任何缩小都可能有助于编译器进行某些优化,从我的头脑中我无法想到任何关于使成员私有的事情。
The teachers were right to tell you to use private and protected to hide implementation and to teach you about information hiding instead of propsing questionable performance optimizations. Try to think of an appropriate design first and of performance second, in 99% of the cases this will be the better choice (even in performance critical scenarios). Performance bottlenecks can appear in a lot of unpredicted cases and are much easier to come by if your design is sound.
To directly answer your question however: any reduction in scope may help the compiler to do certain optimizations, form the top of my head I can not think of any however right now in regards to making members private.
不会。将成员设置为私有或受保护不会提供任何性能优势;当然,对您的设计(信息隐藏)的好处是巨大的。
No. Making members private or protected is not going to provide any performance benefits; of course, the benefits to your design (information hiding) are huge.
一旦你的代码被编译,就不会有
public
、private
和protected
这样的东西,所以它不会影响性能。机器代码中也没有 const 之类的东西(也许 ROM 除外),但编译器可以通过知道值是否可以更改(在某些情况下)来对程序进行一些逻辑优化。
inline
很少有任何效果。它只是给编译器的一个建议,编译器可以自由地忽略它(并且经常这样做)。编译器将根据需要内联函数。There's no such thing as
public
,private
andprotected
once your code is compiled, so it cannot affect performance.There's also no such thing as
const
in machine code (except perhaps ROM), but the compiler can make some logical optimisations to your program by knowing whether a value can change (in some situations).inline
rarely has any effect. It is merely a suggestion to the compiler, which the compiler is free to ignore (and often does). The compiler will inline functions as it sees fit.