The following extract is from an FX Cop warning.
Methods 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 non-virtual call sites to
these members. Emitting non-virtual call sites will prevent a check at
runtime for each call that ensures that the current object pointer is
non-null. This can result in a measurable performance gain for
performance-sensitive code. In some cases, the failure to access the
current object instance represents a correctness issue.
I understand the performance benefits of making private methods static if they don’t access instance data or methods but I’m not sure that in most cases the above advice is good. If you’re writing extremely performance critical code, and you’ve got no choice then to write it in c#, I can understand the sentiment but considering that generally, robust, easier to read, and easy to refactor code is preferred over performance should you actually follow this advice?
The problem I have with private static methods this that when you need to refactor a class I find that static methods make it more difficult to do so. If you have a large number of static methods, and you need to change one to use an instance variable, and that method is used by other private static methods, you end up having to make more changes in order to get this working. Below is an example (please bear in mind this is an minimal implementation just to demonstrate the point):
public class Test
{
private IService myService;
private static void DoSomething()
{
DoSomethingElse();
}
private static void DoSomethingElse()
{
DoSomethingMore();
}
private static void DoSomethingMore()
{
Console.Write("DO SOMETHING");
}
}
If I want to use myService in the DoSomethingMore method, it means I have to make not only that method non-static, but the previous two methods as well. This seems burdensome.
What are other peoples thoughts on this?
When you consider that the entire chain of function calls becomes dependent upon an instance when you modify your
DoSomethingMoremethod, the feeling of the changes being “burdensome” should become “necessary” instead.What you should first consider are the semantics of the methods you’re writing. When you write a method, you need to ask yourself whether the code should be an instance method (because it should semantically be an action associated with a single instance) or a static method (for anything else) and that decision should drive how you write the method.
Until you have measured performance shortcomings that are unacceptable in production code, you should make the method instance or static depending on what makes sense for your domain, not anything else.