Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 710
Vadim Avatar asked Sep 12 '11 08:09

Vadim


People also ask

What is the difference between public/private protected and internal?

public - can be access by anyone anywhere. private - can only be accessed from with in the class it is a part of. protected - can only be accessed from with in the class or any object that inherits off of the class. Nothing is like null but in VB.

What is the difference between public and private methods?

A public method can be invoked from anywhere—there are no restrictions on its use. A private method is internal to the implementation of a class, and it can only be called by other instance methods of the class (or, as we'll see later, its subclasses).

Should I use internal or public?

internal is useful when you want to declare a member or type inside a DLL, not outside that. Normally, when you declare a member as public , you can access that from other DLLs. But, if you need to declare something to be public just inside your class library, you can declare it as internal .

Why use internal instead of private?

internal is an alternative to Java's package-private. internal means that the declarations are visible inside a module. internal provides real encapsulation for the implementation details, while in Java's package-private encapsulation could be broken.


1 Answers

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.

like image 98
Jon Skeet Avatar answered Nov 04 '22 00:11

Jon Skeet