C# – Advantages to Using Private Static Methods


When creating a class that has internal private methods, usually to reduce code duplication, that don't require the use of any instance fields, are there performance or memory advantages to declaring the method as static?


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 there any advantage to declaring the GetInnerXml() methods as static? No opinion responses please, I have an opinion.

Best Solution

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.