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.
public
method from the same assembly it will get inlined just as agressively as a private
one; the only way to get cross-ngen-boundary inlining is with TargettedPatchingOptOutAttribute
. –
Kuehn 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.
© 2022 - 2024 — McMap. All rights reserved.
private static
(as opposed to non-static
) methods? – Inquilinethis
static
is part of the Microsoft.Performance FXCop ruleset; so I assume it does make a difference. – Kuehn