优势使用私有静态方法 [英] Advantages to Using Private Static Methods

查看:104
本文介绍了优势使用私有静态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在创建具有内部私有方法的类,通常是减少code复制,不需要使用任何实例字段中,是否有性能或内存的优势,宣告方法,静态的?

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

是否有任何优势,宣布GetInnerXml()方法为静态?没有意见反应请,我有一个意见。

Is there any advantage to declaring the GetInnerXml() methods as static? No opinion responses please, I have an opinion.

推荐答案

的FxCop规则页在此:

在您标记方法为静态,编译器将发出非虚拟调用点到这些成员。发光非虚拟呼叫网站将prevent在运行时检查为每个确保当前对象的指针非空的呼叫。这可能导致可观的性能增益性能敏感的code。在某些情况下,访问重$ P $当前对象实例失败psents一个正确性的问题。

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.

这篇关于优势使用私有静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆