[英]Is there any difference regarding performance of private, protected, public and internal methods in C# classes?
Is there any difference regarding performance of private
, protected
, public
and internal
methods in C# class? 在C#类中, private
, protected
, public
和internal
方法的性能是否有所不同? I'm interested if one consumes more processor time or RAM. 我很想知道是否要消耗更多的处理器时间或RAM。
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. 在普通的JIT编译情况下,CLR可以仅对访问进行一次验证,然后将其视为理所当然。 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. 我想对于更严格的访问,JIT编译(和IL验证)本身可能会稍慢一些-但我发现很难相信它会很重要。
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. 它将做一些小的改进。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.