性能和静态方法与公共方法 [英] Performance and static method versus public method

查看:33
本文介绍了性能和静态方法与公共方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个辅助方法,它需要一个开始日期和一个结束日期,并通过某些业务逻辑产生一个整数结果.对于给定的数据集,此辅助方法有时会被调用超过 10,000 次(尽管这种情况并不经常发生).

I have a helper method that takes a begin date and an end date and through certain business logic yields an integer result. This helper method is sometimes called in excess of 10,000 times for a given set of data (though this doesn't occur often).

问题:仅考虑性能,将此辅助方法作为某个辅助类的静态方法是否更有效,还是将辅助方法作为类的公共方法更有利?

Question: Considering performance only, is it more efficient to make this helper method as a static method to some helper class, or would it be more gainful to have the helper method as a public method to a class?

静态方法示例:

// an iterative loop
foreach (var result in results) {
    int daysInQueue = HelperClass.CalcDaysInQueue(dtBegin, dtEnd);
}

公共成员方法示例:

// an iterative loop
HelperClass hc = new HelperClass();
foreach (var result in results) {
    int daysInQueue = hc.CalcDaysInQueue(dtBegin, dtEnd);
}

预先感谢您的帮助!

推荐答案

当你调用一个实例方法时,编译器总是不可见地传递一个额外的参数,该参数在this名称下可用.static 方法不代表任何对象调用,因此它们没有 this 引用.

When you call an instance method the compiler always invisibly passes one extra parameter, available inside that method under this name. static methods are not called on behalf of any object, thus they don't have this reference.

我认为将实用方法标记为 static 的好处很少:

I see few benefits of marking utility methods as static:

  • 性能改进,您无需为参考this而付费,而您实际上并不使用它.但是我怀疑您永远不会看到差异.

  • small performance improvement, you don't pay for a reference to this which you don't really use. However I doubt you will ever see the difference.

方便 - 您可以随时随地调用 static 方法,编译器不会强迫您提供一个对象的实例,这不是该方法确实需要

convenience - you can call static method wherever and whenever you want, the compiler is not forcing you to provide an instance of an object, which is not really needed for that method

可读性:实例方法应该对实例的状态进行操作,而不仅仅是对参数进行操作.如果它是一个不需要实例来工作的实例方法,那就很混乱了.

readability: instance method should operate on instance's state, not merely on parameters. If it's an instance method not needing an instance to work, it's confusing.

这篇关于性能和静态方法与公共方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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