Advantages to Using Private Static Methods

Yes, the compiler does not need to pass the implicit this pointer to static methods. Even if you don't use it in your instance method, it is still being passed.


A call to a static method generates a call instruction in Microsoft intermediate language (MSIL), whereas a call to an instance method generates a callvirt instruction, which also checks for a null object references. However, most of the time the performance difference between the two is not significant.

Source: MSDN - https://docs.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2012/79b3xss3(v=vs.110)


When I'm writing a class, most methods fall into two categories:

  • Methods that use/change the current instance's state.
  • Helper methods that don't use/change the current object's state, but help me compute values I need elsewhere.

Static methods are useful, because just by looking at its signature, you know that the calling it doesn't use or modify the current instance's state.

Take this example:

public class Library
{
    private static Book findBook(List<Book> books, string title)
    {
        // code goes here
    }
}

If an instance of library's state ever gets screwed up, and I'm trying to figure out why, I can rule out findBook as the culprit, just from its signature.

I try to communicate as much as I can with a method or function's signature, and this is an excellent way to do that.


From the FxCop rule page on this:

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.

Tags:

C#

Performance