C# 类中私有、受保护、公共和内部方法的性能有什么区别吗?

发布于 2024-12-04 06:02:52 字数 136 浏览 1 评论 0原文

C# 类中的 privateprotectedpublicinternal 方法的性能有什么区别吗?我感兴趣的是是否消耗更多的处理器时间或内存。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

流年里的时光 2024-12-11 06:02:52

我不知道正常调用有任何性能差异;通过动态调用或反射进行访问时,更受限制的访问可能会花费更多的工作,因为可能需要更仔细地验证调用者。在正常的 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.

苏大泽ㄣ 2024-12-11 06:02:52

私有、受保护或公共方法之间的性能不会有明显差异。

如果您专注于优化,可能您应该尝试使瓶颈代码段比面向对象更“程序化”。这会带来小小的改进。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文