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?
Static method example:
// an iterative loop
foreach (var result in results) {
int daysInQueue = HelperClass.CalcDaysInQueue(dtBegin, dtEnd);
}
Public member method example:
// an iterative loop
HelperClass hc = new HelperClass();
foreach (var result in results) {
int daysInQueue = hc.CalcDaysInQueue(dtBegin, dtEnd);
}
Thanks in advance for the help!
When you call an instance method the compiler always invisibly passes one extra parameter, available inside that method under
thisname.staticmethods are not called on behalf of any object, thus they don’t havethisreference.I see few benefits of marking utility methods as
static:small performance improvement, you don’t pay for a reference to
thiswhich you don’t really use. However I doubt you will ever see the difference.convenience – you can call
staticmethod 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 methodreadability: 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.