c# - 使用私有(private)静态方法的优势

标签 c# performance

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

例子:

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

最佳答案

来自FxCop rule page对此:

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.

关于c# - 使用私有(private)静态方法的优势,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/135020/

相关文章:

c - sprintf 的这两种用法在性能上有区别吗?

performance - Julia 的特征分解比 Mathematica 慢 5 倍?

mysql - 用于查询速度的 SQL 索引字符串

c# - 防止代码以随机顺序显示相同的图像?

c# - EF 6 - 如何正确执行并行查询

c# - Web 服务的 Web 异常

C# 内存具有任意数量参数的函数

c# - NHibernate 和 SQL Server 2012 序列

c# - 奇怪的值引用

performance - 从集合中选择随机元素,比线性时间快(Haskell)