使用私有静态方法的优点

时间:2020-03-06 14:44:22  来源:igfitidea点击:

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

例子:

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()方法声明为静态方法有什么好处?请没有意见回应,我有意见。

解决方案

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

这迫使我们记住还必须声明该函数使用的所有类作用域成员都为静态成员,这应节省为每个实例创建这些项的内存。

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

我想说的是私有静态方法的最佳原因是它意味着我们不会意外更改对象(因为没有此指针)。

从FxCop规则页面上:

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.

当我写一个类时,大多数方法分为两类:

  • 使用/更改当前实例状态的方法。
  • 不使用/更改当前对象状态的辅助方法,但可以帮助我计算其他地方需要的值。

静态方法很有用,因为仅通过查看其签名即可知道,调用它不会使用或者修改当前实例的状态。

举个例子:

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

如果某个库状态的实例被搞砸了,而我试图找出原因,那么可以从其签名中排除findBook作为罪魁祸首。

我尝试与方法或者函数的签名进行尽可能多的交流,这是实现此目的的一种极好的方法。