开发者

Is there any difference regarding performance of private, protected, public and internal methods in C# classes?

开发者 https://www.devze.com 2023-04-04 17:58 出处:网络
Is there any difference regarding performance of pri开发者_如何学编程vate, protected, public and internal methods in C# class? I\'m interested if one consumes more processor time or RAM.I\'m not aware

Is there any difference regarding performance of pri开发者_如何学编程vate, protected, public and internal methods in C# class? I'm interested if one consumes more processor time or 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. 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消