当创建一个具有内部私有方法(通常是为了减少代码重复)的类时,不需要使用任何实例字段,将方法声明为静态是否有性能或内存优势?

例子:

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;
}

将GetInnerXml()方法声明为静态有什么好处吗?请不要发表意见,我有自己的看法。


当前回答

对静态方法的调用以Microsoft中间语言(MSIL)生成调用指令,而对实例方法的调用则生成callvirt指令,该指令还检查空对象引用。然而,在大多数情况下,两者之间的性能差异并不显著。

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

其他回答

是的,编译器不需要将隐式this指针传递给静态方法。即使你没有在你的实例方法中使用它,它仍然被传递。

这迫使您记住将函数使用的任何类作用域成员也声明为静态的,这将节省为每个实例创建这些项的内存。

As has already been stated, there are many advantages to static methods. However; keep in mind that they will live on the heap for the life of the application. I recently spent a day tracking down a memory leak in a Windows Service... the leak was caused by private static methods inside a class that implemented IDisposable and was consistently called from a using statement. Each time this class was created, memory was reserved on the heap for the static methods within the class, unfortunately, when the class was disposed of, the memory for the static methods was not released. This caused the memory footprint of this service to consume the available memory of the server within a couple of days with predictable results.

对静态方法的调用以Microsoft中间语言(MSIL)生成调用指令,而对实例方法的调用则生成callvirt指令,该指令还检查空对象引用。然而,在大多数情况下,两者之间的性能差异并不显著。

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

由于没有传递this参数,它会稍微快一些(尽管调用该方法的性能成本可能比节省的成本要高得多)。

我想说,我能想到的私有静态方法的最好理由是,它意味着你不能意外地改变对象(因为没有this指针)。