This is a purely hypothetical question.
Say I create a class method that contains no references to instance variables or other resources. For example (C#):
protected string FormatColumn(string value, int width)
{
return value.Trim().PadLeft(width);
}
As far as I can see, there is absolutely no reason why this method could not be declared static:
- It only uses method-scope variables.
- It doesn’t
override
a base class method. - It’s not
virtual
orabstract
.
My questions are:
Is there any benefit to calling a static method over an instance method?
If so, why doesn’t the compiler implicitly convert this to a static method?
I’m certain I’ve missed some key point here. Any ideas?
You should read this article about Code Analysis rule #CA1822, which states:
Members that do not access instance data or call instance methods can
be marked as static (Shared in Visual Basic). After you mark the
methods as static, the compiler will emit nonvirtual call sites to
these members. Emitting nonvirtual call sites will prevent a check at
runtime for each call that makes sure that the current object pointer
is non-null. This can achieve a measurable performance gain for
performance-sensitive code. In some cases, the failure to access the
current object instance represents a correctness issue.
2
Static methods are usually utility operations shared among instances of a specific class, a.k.a utility methods. For example the String.Join()
method which takes an array and join the elements by using a separator character or string.
So, my rule is that if the method is a utility shared functionality specific to instances of that class then it can be static.
It would be weird to have to create a new string
in order to use the Join()
method to join multiple strings into a new one.
This is an opinion rather than sure solid facts, I present it here as it may be of help. here it goes:
One main concern with statics is thread safety. Static fields within the static classes (rather than static methods themselves) may cause the unexpected results when multiple threads are in action.
Is there any benefit to calling a static method over an instance method?
Yes, assuming the method uses an instance variable of some sort such as a counter for example, If you do this you are sure that the variables used within the instance method will be allocated separately for each object. You may choose to lock your object and the results would be guaranteed to be correct when multiple threads access it.
why doesn’t the compiler implicitly convert this to a static method?
I really don’t know for sure what the compiler does, but if it does not turn such methods to static methods, one reason for that may be because of thread safety. This is because, the compiler will have to tweak the code with locks to make it return the correct result. Locks slows down the execution in mulch-threaded processing.
Edit: Fixed a type as suggested by @WinstonEwert’s comment.
9
Since your method is not final (sealed)nor private, it means that it could be overridden by a child class, which is at least one reason why the compiler can’t transform that method into a static method.
Now, if you make it either private or final (sealed), then there’s no reason not to make it static, but then the performance improvement would be minimal, since it’s only passing one less parameter (no need for virtual call if method is private and/or final)
Also, as Bernard said, that would also remove the null check on the instance, which could still occur even with a private or a protected method.
For example with this code :
public static staticMethod() {
MyClass class= ...
class.FormatColumn("a", 1) // this should throw an exception if column is null, but not when FormatColumn becomes static
}
for a private method, I guess the compiler could check all calls from a static method and add necessary null pointer checks, since it has access to the whole class, but then we would probably lose in jumps what we saved by adding an additional pointer to this
.
2