C# 类中私有、受保护、公共和内部方法的性能有什么区别吗?
C# 类中的 private
、protected
、public
和 internal
方法的性能有什么区别吗?我感兴趣的是是否消耗更多的处理器时间或内存。
Is there any difference regarding performance of private
, protected
, public
and internal
methods in C# class? I'm interested if one consumes more processor time or RAM.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不知道正常调用有任何性能差异;通过动态调用或反射进行访问时,更受限制的访问可能会花费更多的工作,因为可能需要更仔细地验证调用者。在正常的 JIT 编译情况下,CLR 只能验证一次访问,然后就认为是理所当然的。我想对于更严格的访问,JIT 编译(和 IL 验证)本身可能会稍微慢一些 - 但我发现很难相信它会很重要。
这绝对不应该成为决定使用哪种可访问性的一个因素,即使不知何故存在一些我不知道的微小性能差异。如果您相信您可以通过使可访问性不同于您的设计的“自然”可访问性来实现性能优势,那么您绝对应该对之前/之后的情况进行基准测试 - 我怀疑您将很难找到一个真实世界的情况,差异是可以可靠测量的。
同样的建议适用于各种微观优化:无论如何,这几乎都不是一个好主意,并且绝对应该只在仔细测量的情况下进行。
I'm not aware of any performance difference for normal invocation; it's possible that more restricted access will take a little more work when accessing via dynamic invocation or reflection as the caller may need to be validated more carefully. In the normal JIT-compiled case the access can be validated by the CLR just once and then taken for granted. I guess it's possible that the JIT compilation (and IL verification) itself could be slightly slower for more restrictive access - but I find it hard to believe it would be significant.
This should absolutely not be a factor in determining which accessibility to use, even if somehow there is some tiny performance difference I'm unaware of. If you believe you may be able to achieve a performance benefit by making the accessibility something other than the "natural" one for your design, you should definitely benchmark the before/after case - I suspect you'll be hard-pressed to find a real-world situation where the difference is reliably measurable.
The same sort of advice goes for all kinds of micro-optimization: it's almost never a good idea anyway, and should definitely only be undertaken within careful measuring.
私有、受保护或公共方法之间的性能不会有明显差异。
如果您专注于优化,可能您应该尝试使瓶颈代码段比面向对象更“程序化”。这会带来小小的改进。
There will be no measurable difference in performance between private, protected or public methods.
If you focus on optimization, possibly you should try making your bottleneck piece of code more "procedural" than object-oriented. It would do small improvement.