Coder Perfect

Private Static Methods Have a Lot of Benefits

Problem

Is there a performance or memory benefit to defining a method as static when designing a class with internal private methods that don’t require the use of any instance fields, usually to prevent code duplication?

Example:

foreach (XmlElement element in xmlDoc.DocumentElement.SelectNodes("sample"))
{
    string first = GetInnerXml(element, ".//first");
    string second = GetInnerXml(element, ".//second");
    string third = GetInnerXml(element, ".//third");
}

private static string GetInnerXml(XmlElement element, string nodeName)
{
    return GetInnerXml(element, nodeName, null);
}

private static string GetInnerXml(XmlElement element, string nodeName, string defaultValue)
{
    XmlNode node = element.SelectSingleNode(nodeName);
    return node == null ? defaultValue : node.InnerXml;
}

Is it beneficial to declare the GetInnerXml() functions as static? Please don’t respond with an opinion; I have one.

Asked by NerdFury

Solution #1

The following is taken from the FxCop rule page:

Answered by Scott Dorman

Solution #2

Most methods fall into one of two categories when I’m writing a class:

Static methods are handy because you can tell by glancing at their signature that the person calling them does not utilize or modify the state of the current instance.

Take this example:

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

If the state of a library instance is ever messed up, and I’m trying to figure out why, I can rule out findBook as the culprit based on its signature alone.

I aim to communicate as much as possible with the signature of a method or function, and this is a great approach to do it.

Answered by Neil

Solution #3

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

Answered by Marek Takac

Solution #4

Yes, static methods do not require the compiler to pass the implicit this pointer. It is still passed even if you don’t utilize it in your instance method.

Answered by Kent Boogaart

Solution #5

Because this argument isn’t passed, it’ll be a little faster (although the performance cost of calling the method is probably considerably more than this saving).

The best reason I can think of for private static methods is that it prevents you from changing the object by accident (because there is no this pointer).

Answered by Free Wildebeest

Post is based on https://stackoverflow.com/questions/135020/advantages-to-using-private-static-methods