简体   繁体   中英

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? 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM